【发布时间】:2019-11-17 09:46:39
【问题描述】:
我正在尝试编写一个程序,该程序以用户使用牛顿法提供的指定精度 (k) 计算整数 (n) 的平方根。该程序运行良好,但我注意到我认为是一个四舍五入的问题。有人可以帮我解决这个问题吗?
例如:
- 对于输入:n = 81 和 k = 7 / 对于输入:n = 87026 和 k = 11
- 程序正在打印:9.0000001 / 程序正在打印:295.00169491039
- 我要打印的内容:9.0000000 / 我要打印的内容:295.00169491038
这是我的代码:
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);
【问题讨论】:
标签: java rounding bigdecimal