[removed] PI (π) Calculator

前端 未结 5 1860
忘了有多久
忘了有多久 2021-01-26 04:43

Is there a way to calculate pi in Javascript? I know there you can use Math.PI to find pie like this:

var pie = Math.PI;
alert(pie); // output \"3.1         


        
5条回答
  •  我在风中等你
    2021-01-26 05:29

    You can approximate the value of π through the use of Monte Carlo simulation. Generate a random X and Y each in the range [-1,1] Then the likelihood (X, Y) is in the unit circle centered at the origin is π/4. More samples yields a better estimate of its value. You can then estimate π by comparing the ratio of samples in the unit circle with the total number of samples and multiply by 4.

    this.pi = function(count) {
        var inside = 0;
    
        for (var i = 0; i < count; i++) {
            var x = random()*2-1;
            var y = random()*2-1;
            if ((x*x + y*y) < 1) {
                inside++
            }
        }
    
        return 4.0 * inside / count;
    }
    

提交回复
热议问题