public static int newtonCount(double x, double err)
Determines the number of iterations of Newton's method required to approximate the square root of x within the given bound. Newton's method starts out by setting the initial approximate answer to x. Then in each iteration, answer is replaced by the quantity (answer + x / answer) / 2.0. The process stops when the difference between x and (answer * answer) is strictly less than the given bound err. The method returns the number of iterations required. The given value x must be non-negative.
For example, given x = 10 the first three iterations of Newton's method produce the approximate values 5.5, 3.66, and 3.20. Those three values squared are 30.29, 13.39, and 10.21, respectively. Therefore newtonCount(10, 1.0) returns 3, since it takes 3 iterations to get the result 10.21 that is within 1.0 of x. On the other hand, newtonCount(10, 200) returns 0, since 10 * 10 = 100 is already within 200 units of x = 10.
Parameters:
x - value whose square root is to be approximated
err - given bound for the approximation
Returns:
number of iterations required to get an approximation whose square is within the given bound of x
/*Function to determines the number of iterations of Newton's method required to approximate the square root of x within the given bound.*/
public static int newtonCount(double x,double err){
int iteration_counter=0; /*To determines the number of iterations*/
double answer=x;
while((answer*answer)-x>=err){ /*To ensure the difference between x and (answer * answer) is strictly less than the given bound err*/
iteration_counter++; /*Iteration counter increment*/
answer=(answer+ (x/answer))/2.0; /*updated answer*/
}
return iteration_counter;
}
//Have any doubt ask in comment box .
Get Answers For Free
Most questions answered within 1 hours.