Reputation: 61
this program is supposed to take a non negative integer and find the square root
The square root of a non-negative number n can be calculated successive
approximations. At each step, a new approximation is calculated as follows:
next approximation = (n / current + current) / 2
The process of approximation continues until the value is close enough, that is, the difference between (current * current) and n is small enough to be acceptable. However when i go print my answer nothing comes up. what am i doing wrong. is my loop not working correctly?
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class Squareroot1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a non negative integer: ");
double n = in.nextInt();
double result = approx(n);
/*double current = result;
while ((current * current)- n == Math.sqrt(n)) {
double nextapproximation = (n/current + current)/2;
nextapproximation = current;
System.out.println(nextapproximation);
}*/
System.out.println( result);
}
public static double approx(double val) {
double current = val;
double approximation = (val / current + current) / 2;
return approximation;
}
}
Upvotes: 1
Views: 1225
Reputation: 4191
You have a few issues:
1) Your while loop condition should be:
while ((current * current) - n != 0)
2) You are not setting current
to the value of the nextapproximation
3) You are not printing out the final result (which should be current).
The code:
double result = aprox(n);
double current = result;
while ((current * current) - n != 0)
{
double nextapproximation = (n / current + current) / 2;
// Stop infinite loop
if (nextapproximation == current)
{
break;
}
current = nextapproximation;
System.out.println(current);
}
System.out.println("Result: " + current);
Test Run:
Enter a non negitive integer: 23
6.958333333333333
5.131861277445109
4.806832989404423
4.795844112917605
4.795831523329245
4.795831523312719
Result: 4.795831523312719
EDIT:
You don't need the aprox
method and you don't need the result
variable.
Before the while loop simply do:
double n = in.nextInt();
double current = (n / n + n) / 2;
Upvotes: 1