Java使用Nilakantha级数和BigDecimal错误计算pi
我一直在开发一个小程序,使用Nilakanta级数、BigDecimal和其他人的代码计算pi,但由我编辑
以下是迄今为止的代码:
package com.waitdev.pi;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
public class MainProgram {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of calculations you would like to do");
long no = Long.parseLong(reader.readLine());
long step = 0;
BigDecimal ans = new BigDecimal(3);
Double j = 2.0;
BigDecimal pi = new BigDecimal(0.0);
while (true) {
step++;
if ((step % 2) == 1) {
ans.add(new BigDecimal(4.0 / (1.0 * j * (j + 1) * (j + 2))));
} else {
ans.subtract(new BigDecimal(4.0 / (1.0 * j * (j + 1) * (j + 2))));
}
j += 2;
pi = ans;
if (step >= no)
break;
}
System.out.println("Calculated: " + pi);
BigDecimal enew = pi;
double error = enew.divide(3.1415926535897932);
if (error >= 1) {
double bigerror = 2 - error;
System.out.println("Your accuracy is: " + bigerror * 100 + "%");
System.out.println(step);
} else {
System.out.print("Your accuracy is: ");
System.out.print(error * 100);
System.out.println("%");
System.out.println(step);
}
}
}
当我运行这个程序时,结果是这个崩溃报告:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method divide(BigDecimal) in the type BigDecimal is not applicable for the arguments (double)
at com.waitdev.pi.MainProgram.main(MainProgram.java:38)
似乎是在这一部分:
double error = enew.divide(3.1415926535897932);
在eclipse中,这一行表示“BigDecimal类型中的方法divide(BigDecimal)不适用于参数(double)”
顺便说一句,我不熟悉BigDecimal,也不熟悉Java,但我知道一些基础知识
# 1 楼答案
我认为你需要使用大十进制。像这样把你团团围住