Help with Square root function and Overload(calc error)
Here is what i have to do.
1. Create a new class called SlowMath that contains a static function to find the square root of a given integer n using the iterative algorithm
x i +1 = 0.5(x i + n/x i) x0 = n/2.
The user will also supply a parameter indicating the number of iterations. Hint: Use a for loop to perform the iteration.
Note: For part 1, create a static method called sqrtIterate that takes two arguments, the number to be operated on (a double), and another number (an int) that specifies the number of iterations
2. Overload your square root function by providing another call that does the same thing but continues to iterate until difference between the actual value and the calculated value is less than a user provided error (use Math.sqrt to calculate the actual value). Return the number of iterations required. Hint: Use a while loop with the key test as the while conditional.
Note: For part 2, create a another method with the same name but with 2 double arguments (the first the number, the second the error). This method keeps iterating until the actual error (computed as the difference between the current value and the actual square root given by Math.sqrt) is less than the error parameter supplied to the method. Hope this helps.
Here is what i did for one:
import java.util.*;
public class SlowMath {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number for square root: ");
double n = in.nextDouble();
System.out.println("Number of iterations: ");
int numIt = in.nextInt();
double x = n / 2;
double y = 0;
for (int i = 0; i < numIt; i++) {
y = 0.5 * (x + n / x);
x = y;
}
System.out.println("Approximation of Square root: " + x);
}
}
Here is what i did for 2...so far. Need help completing it.
import java.util.*;
public class Overload {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number for square root: ");
double n = in.nextDouble();
System.out.println("Number of iterations: ");
int numIt = in.nextInt();
double x = n / 2;
double y = 0;
for (int i = 0; i < numIt; i++) {
y = 0.5 * (x + n / x);
x = y;
}
double error = 0;
double threshold = 0;
while (error > threshold) {
error = x - Math.sqrt(n);
if(x < Math.sqrt(n)){
error = Math.abs(x - Math.sqrt(n));
}
else if(error > Math.sqrt(n)){
error = Math.abs(x - Math.sqrt(n));
}
else{
error = 0;
}
}
System.out.println("Approximation of Square root: " + x);
System.out.println("Error equals: " + error);
}
}
Can anyone help me, i think i'm almost done, but i just can't figure out how to show, or calculate the error properly