Skip to content

Instantly share code, notes, and snippets.

@biaocy
Created September 25, 2017 07:54
Show Gist options
  • Save biaocy/885d4ed3a24f9637ffa80174464336da to your computer and use it in GitHub Desktop.
Save biaocy/885d4ed3a24f9637ffa80174464336da to your computer and use it in GitHub Desktop.
割圆术(刘徽)求π
function cx(lastM, r) { //求圆心到等边形的垂直距离
return Math.sqrt(r-Math.pow(lastM/2, 2));
}
function cm(lastM, r) { //求等边形边长
var x = cx(lastM, r); //圆心到等边形边的垂直距离
return Math.sqrt(Math.pow(r-x, 2) + Math.pow(lastM/2, 2));
}
function pi(t) {
var n = 6; //等边形的边数
var m = 1; //等边形边长
var r = 1; //圆半径
var p = (n * m) / (r * 2); //pi π
while(t-- > 0) {
n *= 2;
m = cm(m, r);
p = (n * m) / (r * 2);
}
console.log("n:%s", n);
console.log("p:%s", p);
return p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment