Popular Posts

Wednesday, March 16, 2011

Find Square root using Babylonian method(Efficient)


Perhaps the first algorithm used for approximating \sqrt S is known as the "Babylonian method", named after the Babylonians, or "Heron's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first explicit description of the method. It can be derived from (but predates) Newton's method. This is a quadratically convergentalgorithm, which means that the number of correct digits of the approximation roughly doubles with each iteration. It proceeds as follows:
  1. Begin with an arbitrary positive starting value x0 (the closer to the root, the better).
  2. Let xn+1 be the average of xn and S / xn (using thearithmetic mean to approximate the geometric mean).
  3. Repeat step 2 until the desired accuracy is achieved.
It can also be represented as:
x_0 \approx \sqrt{S}.
x_{n+1} = \frac{1}{2} \left(x_n + \frac{S}{x_n}\right),
\sqrt S = \lim_{n \to \infty} x_n.
This algorithm works equally well in the p-adic numbers, but cannot be used to identify real square roots with p-adic square roots; it is easy, for example, to construct a sequence of rational numbers by this method that converges to + 3 in the reals, but to − 3 in the 2-adics.
Java Code :
public static double getSquareRoot(double s) {
double Xn = 2.0;
double lastXn = 0.0;
while (Xn != lastXn) {
lastXn = Xn;
Xn = (Xn + s / Xn) / 2.0;
}
return Xn;
}

 Refer : http://www.ardendertat.com/2012/01/26/programming-interview-questions-27-squareroot-of-a-number/

No comments:

Post a Comment