我想制作一个快速生成器(如果可能的话,在Java中),它给我Pi(当然还有小数)。 我已经制作了一个,它使用for循环和BigDecimals:
BigDecimal pi;
pi = new BigDecimal("0");
BigDecimal divide = new BigDecimal("1");
long max = <Any Number>;
for (long l = 1; l < max; l++) {
BigDecimal two = new BigDecimal("2"); //it gave me an error if it wasn't a BigDecimal.
BigDecimal four = new BigDecimal("4");
BigDecimal divide2 = divide.add(two);
BigDecimal divideend = four.divide(divide, 50, BigDecimal.ROUND_HALF_UP);
BigDecimal divideend2 = four.divide(divide2, 50, BigDecimal.ROUND_HALF_UP);
pi = pi.add(divideend);
pi = pi.subtract(divideend2);
System.out.println(pi.toString() + " " + i + " of " + max);
divide = divide.add(vier);
}
System.out.println(pi.toString() + " finished.");
这个问题是:
我想让它运行500.000.000倍(5亿),它只需要超过5个小时并且“仅”大约12个正确的小数位...是否有更快的解决方案?
import java.math.BigDecimal;
public class Pitest3 {
public static void main(String[] args) {
BigDecimal pi = new BigDecimal("3");
long l = 1l;
long max = 100000; //How often, the more, the more exact
BigDecimal axbxc;
BigDecimal divide1;
BigDecimal divide2;
BigDecimal divide3;
divide1 = new BigDecimal("2");
divide2 = new BigDecimal("3");
divide3 = new BigDecimal("4");
BigDecimal four = new BigDecimal("4");
BigDecimal sumthing1;
BigDecimal sumthing2;
BigDecimal two = new BigDecimal("2");
BigDecimal sumthing3;
BigDecimal sumthing4;
while (l < max) {
sumthing1 = divide1.multiply(divide2);
axbxc = sumthing1.multiply(divide3);
sumthing2 = four.divide(axbxc, 100, BigDecimal.ROUND_HALF_UP);
pi = pi.add(sumthing2);
divide1 = divide1.add(two);
divide2 = divide2.add(two);
divide3 = divide3.add(two);
sumthing3 = divide1.multiply(divide2);
axbxc = sumthing3.multiply(divide3);
sumthing4 = four.divide(axbxc, 100, BigDecimal.ROUND_HALF_UP);
pi = pi.subtract(sumthing4);
divide1 = divide1.add(two);
divide2 = divide2.add(two);
divide3 = divide3.add(two);
System.out.println(pi.toString() + " " + l + " of " + max)
l++;
}
System.out.println(pi.toString() + " finished!");
}
}