我最近制作了一个与 Math.BigDecimal 配合使用的基本 Pi 计算器。它输出到文本文件,计算速度非常快,但即使是 BigDecimal 也有其局限性。我想知道更精确的数字的基本代码是什么(并不是任何代码实际上都需要它)。这是Pi代码:
package mainPack;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static BigDecimal piDigCalc(int i){
double o = (double)i;
BigDecimal ret = new BigDecimal((1/(Math.pow(16.0D, o))*((4/((8*o) + 1))-(2/((8*o) + 4))-(1/((8*o) + 5))-(1/((8*o)+6))))); //Just the code for a hexdigit of Pi.
return ret;
}
public static void main(String[] args) throws IOException {
System.out.println("Enter accuracy:");
Scanner s = new Scanner(System.in);
int acc = s.nextInt();
s.close();
BigDecimal Pi = new BigDecimal(0);
for(int i = 0; i < acc; i++){
Pi = Pi.add(piDigCalc(i));
}
Path file = Paths.get("C:\\tmp\\PI.txt");
String pi = "" + Pi;
Files.write(file, pi.getBytes());
System.out.println("File has been saved at "+ file.toString());
}
}