Leedwon

Untitled

Nov 24th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. // finds square root
  5. double squareRoot(double x);
  6.  
  7. // checks if x/g = g if so then its the square root
  8. bool isCloseEnough(double xDividedByG, double g);
  9.  
  10. // returns average of x / g and g
  11. double betterGuess(double x, double g);
  12.  
  13. //g should always be 1 tests if x/g = g so calls isCloseEnough here
  14. double test(double x, double g);
  15.  
  16.  
  17. int main() {
  18.  
  19.     std::cout << squareRoot(4);
  20.  
  21.     return 0;
  22. }
  23.  
  24. double test(double x, double g) {
  25.     if (isCloseEnough(x / g, g))
  26.         return g;
  27.     else
  28.         test(x, betterGuess(x, g));
  29. }
  30.  
  31. bool isCloseEnough(double xDividedByG, double g) {
  32.     return (abs(xDividedByG - g) < .001);
  33. }
  34.  
  35. double betterGuess(double x, double g) {
  36.     return (g + x/g) / 2;
  37. }
  38.  
  39. double squareRoot(double x) {
  40.     return test(x, 1);
  41. }
Advertisement
Add Comment
Please, Sign In to add comment