格里高利公式用来求π的近似值,公式如下
π/4=1−1/3+1/5−1/7+...
function pi(){
let pi4 = 0;
let flag = 1;
let temp = 0;
let count = 0;//统计循环次数
while(true){
temp = Math.pow(-1,flag+1) * (1/ (2*flag -1 ))
if(Math.abs(temp) < 0.0000001){
break
}else{
pi4 += temp;
flag++
count ++
}
}
console.log(pi4*4,count)
}精确到10-7时,循环次数能达到5百万次。