I am trying to write a program that calculates the square root of an integer (n) with a specified precision (k) provided by user using the newton's method. The program is working fine however I am noticing what I think is a rounding issue. Can someone help me solve this?
For example:
- for input: n = 81 and k = 7 / for input: n = 87026 and k = 11
- program is printing: 9.0000001 / program is printing: 295.00169491039
- what I want to print: 9.0000000 / what I want to print: 295.00169491038
Here is my code:
Scanner userInput = new Scanner(System.in);
//print instructions and scan user input
System.out.println("~ This program computes the square root of an integer ~");
System.out.print("\n" + "Enter a non-negative integer [not greater than 1 billion (10^9)] n: ");
int n = userInput.nextInt();
System.out.print("\n" + "Enter a non-negative integer [not greater than 10 thousand (10^4)] k: ");
int k = userInput.nextInt();
userInput.close();
// declaring and converting variables
int p = (k + 1);
BigDecimal num = new BigDecimal(n);
BigDecimal guess = new BigDecimal(n);
BigDecimal newGuess;
BigDecimal sqrt;
// calculating error using int p
BigDecimal error = BigDecimal.ONE.movePointRight(-p);
// calculating guess using int p
BigDecimal diff = BigDecimal.ONE.scaleByPowerOfTen(p);
// newton's loop
while (diff.compareTo(error) == 1) {
newGuess = guess.subtract(
((guess.multiply(guess)).subtract(num))
.divide(guess.add(guess), k, RoundingMode.DOWN));
diff = newGuess.subtract(guess);
if (diff.signum() == -1) {
diff = diff.abs();
}
guess = newGuess;
}
// printing sqrt to screen
sqrt = guess;
System.out.println("loop calculated: " + "\n" + sqrt);