最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - nth digit of Pi - Stack Overflow

programmeradmin0浏览0评论

I've been searching for hours trying to find an algorithm to get the nth digit of pi for JavaScript.

I know I can use 2*Math.acos(0) or Math.PI to get PI but I need to find the nth digit.

How would one get the nth digit of PI without a hard-coded number already in it?

I've been searching for hours trying to find an algorithm to get the nth digit of pi for JavaScript.

I know I can use 2*Math.acos(0) or Math.PI to get PI but I need to find the nth digit.

How would one get the nth digit of PI without a hard-coded number already in it?

Share Improve this question asked Jun 28, 2014 at 14:50 SpedwardsSpedwards 4,49216 gold badges59 silver badges119 bronze badges 7
  • 1 A simple way would be trying to taylor series and approximating it as much as you need. How good is your mathematics? – Benjamin Gruenbaum Commented Jun 28, 2014 at 14:52
  • possible duplicate of How is PI calculated? – jcaron Commented Jun 28, 2014 at 14:53
  • Also see: bellard/pi – C. K. Young Commented Jun 28, 2014 at 14:53
  • That's a different language – Benjamin Gruenbaum Commented Jun 28, 2014 at 14:53
  • 1 @adeneo Math.PI doesn't return anything past "3.141592653589793". – Spedwards Commented Jun 28, 2014 at 15:15
 |  Show 2 more ments

1 Answer 1

Reset to default 5

Here is a rather simple way assuming some first year calculus.

You can approximate functions by derivating them over and over and understanding their slope - and then building a polynomial around them such that the polynomial approximates their behavior well enough. If you keep doing this for as long as you can you get something called their taylor sequence. If a function is "well behaved" enough - such as the sine function, you can approximate it rather easily.

Here is the expansion of the sine function, taken from Wikipedia (CC wikipedia)

You can e up with this by derivating sin(x) n times and approximating it. Read more on the subject here.

One helpful analysis it and e up with the inverse tangent function Math.atan:

This is useful since putting x = 1 we know Math.atan(1) = Pi/4.

So, let's write our getPi:

function getPi(){
    var sum = 0;
    for(var n = 0; n < 100000000; n++){
        var mult = (n%2 === 0) ? 1 : -1; // -1^n
        sum += mult * (1 / (2*n+1));
    }
    return sum * 4; // to get pi
}
getPi(); // 3.141592643589326

The more iterations you perform, the better the accuracy you'll get. There are faster ways to calculate Pi, this is just an example that requires some - but not a huge amount of math. As mentioned - it works by approximating the atan function with a polynomial.

Note : we have bigger issues with larger numbers since JavaScript double precision numbers are bounded. We ignore that in this answer.

发布评论

评论列表(0)

  1. 暂无评论