Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- // finds square root
- double squareRoot(double x);
- // checks if x/g = g if so then its the square root
- bool isCloseEnough(double xDividedByG, double g);
- // returns average of x / g and g
- double betterGuess(double x, double g);
- //g should always be 1 tests if x/g = g so calls isCloseEnough here
- double test(double x, double g);
- int main() {
- std::cout << squareRoot(4);
- return 0;
- }
- double test(double x, double g) {
- if (isCloseEnough(x / g, g))
- return g;
- else
- test(x, betterGuess(x, g));
- }
- bool isCloseEnough(double xDividedByG, double g) {
- return (abs(xDividedByG - g) < .001);
- }
- double betterGuess(double x, double g) {
- return (g + x/g) / 2;
- }
- double squareRoot(double x) {
- return test(x, 1);
- }
Advertisement
Add Comment
Please, Sign In to add comment