1 The following defines a function that calculates an approx
1) The following defines a function that calculates an approximation of the square root of a number, starting with an approximate answer (approx), within the specified tolerance (tol).
a) What limitations must be placed on the values of the arguments if this function is to work correctly?
b) Write a recursive method sqrRoot that implements the function.
c) Write a nonrecursive version of the method sqrRoot.
d) Write a driver to test the recursive and iterative versions of the method sqrRoot.
( Can you write it in java language and make it as simple as possible and also can just kind of mention different parts (a,b,c,d), please? Thank you)
Solution
A function call to itself is called the recursive function.
recursive method for the approximantion :
private static double AppRoot_Recursive(double num, double approx, double tol)
{
if(Math.abs(approx*approx - num) <= tol){
return approx;
}
else
{
approx = (approx*approx + num)/(2*approx);
}
return 1.0 * (AppRoot_Recursive(num, approx, tol));
}
Non recursive method for findout the square route of a number:
public double squareRoot = input_number/2;
do
{
n=squareRoot;
squareRoot = (n + (input_number/n))/2;
}
while((n-squareRoot)!=0);
Program:
import java.util.Scanner;
public class ApproxRoot
{
public static void main(String[] args)
{
double num;
double sqrt;
Scanner input = new Scanner(System.in);
do
{
System.out.println(\"Enter a number to find the approximate square root of a number: \");
num = input.nextInt();
if(num == -1) {
System.exit(0);
}
System.out.println(\"The Square Root of \" + num + \" is \" + AppRoot_Recursive(num, 1, 1));
System.out.println(\"to exit give input zero -1\");
}
while(num != -1);
}
private static double AppRoot_Recursive(double num, double approx, double tol)
{
if(Math.abs(approx*approx - num) <= tol){
return approx;
}
else
{
approx = (approx*approx + num)/(2*approx);
}
return 1.0 * (AppRoot_Recursive(num, approx, tol));
}
}
Output is :

