C++ implementation of Babylonian Method – method to calculate square root of positive numbers.

Enter number to square root: 3
Enter precision 0.0000000000001
sqrt(3) = 0.3
sqrt(3) = 5.15
sqrt(3) = 2.86626
sqrt(3) = 1.95646
sqrt(3) = 1.74492
sqrt(3) = 1.7321
sqrt(3) = 1.73205
#include <iostream>

// © 2018 TheFlyingKeyboard and released under MIT License 
// theflyingkeyboard.net

using namespace std;

int main() {
  double number = 0.0;
  double precision = 0.0;

  cout << "Enter number to square root: ";
  cin >> number;

  cout << "Enter precision ";
  cin >> precision;

  if (number < 0) {
    cout << "number must be >= 0" << endl;
    return 1;
  }

  if (number == 0) {
    cout << "sqrt(0) = 0" << endl;
    return 0;
  }

  double x = number / 10;
  double y = number / x;

  do {
    cout << "sqrt(" << number << ") = " << x << endl;
    x = (x + y) / 2;
    y = number / x;
  } while (x - y > precision);

  int a;
  cin >> a;

  return 0;
}

 



C++ Babylonian Method – SQRT()
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close