Square
Root
Complete Source
Code
/*
This program will approximate the square root of a given nonnegative real
number This approximation can then be compared to the value which is
computed by the built in function Math.sqrt(). The algorithm that is
implemented here can be described as follows. First x represents the given
number. If the square of x is greater than x, then we know that x is not
the square root. So, we shall try the square of x/2 instead. If this value
is also greater than x, then we shall try the square of x/4 next. If
instead, this value is less than x, then we shall square the number which
lies halfway between x/2 and x (i.e. 3x/4) and see if that's greater than
x or not. By stepping back and forth in this fashion and squaring all the
midpoints, we will obtain increasingly better approximations.
In order to implement this procedure, we need a variable s which stores
the current approximation, a variable t which s can get arbitrarily close
to with each successive midpoint trial, and a variable temp which keeps
track of the previous approximation. This variable is needed in order to
shift the direction of approach back and forth. The approximations are
then carried out by two nested while loops which are meant to handle each
direction in turn. */
public class SquareRoot {
public static void main(String[]
args) {
double x, s, t, temp;
System.out.println();
while (true) {
System.out.print("Please enter
a nonnegative real number: ");
x = TextIO.getlnDouble();
if (x >= 0) break;
}
s = x;
temp = 0;
if (x > 0 && x < 1) s = 1/s;
while (Math.abs(s*s-x) > 0.00000001) {
t = temp;
while (s*s > x) {
temp = s;
s = (s+t)/2;
}
t = temp;
while (s*s < x) {
temp = s;
s = (s+t)/2;
}
}
System.out.println("\nThe approximate square root
of " + x + " is " + s + ".");
System.out.println("The actual square root of " +
x + " is " + Math.sqrt(x) + ".");
}
} |