基于泰勒公式编写一个小程序计算圆周率,当最后一项的值小于给定域值时结束
(π/4=
该程序使用了莱布尼茨级数,将pi的值计算到了0.0001的精度。程序将持续计算,直到误差小于指定容忍度。
public class CalculatePi {
public static void main(String[] args) {
double pi = calculatePi(0.0001);
System.out.println("π = " + pi);
}
public static double calculatePi(double error) {
double pi = 0;
double temp = 1;
int n = 1;
while (temp > error) {
temp = 1.0 / (2 * n - 1);
if (n % 2 == 0) {
pi -= temp;
} else {
pi += temp;
}
n++;
}
return pi * 4;
}
}