how to caculate the π


  • 0
    W

    sorry guys , this is not in google's interview but it's a real interview topic.The company just ask me how to caculate the π. that's all!!!!


  • 0

    Could you please add the company as tag? Please read the instructions on how to do so.


  • 0
    A

    You can do it with a random number generator.
    We need a random number generator which can generate numbers from 0 to 1.
    Have two counters say cnt1 and cnt2;
    Generate two numbers at a time as x ,y respectively, their distance from 0,0 if less than equal to 1, we call this number as accepted and increase cnt1 and cnt2( this counts total number generated.
    you can do this for any number of times like 10 or so.
    the ratio of cnt1/cnt2 gives you area of a quarter with radius 1. Multiply it with 4 and you will have the value of pie.


  • 0
    C

    Let's assume you have a square of length 1x1. Draw a circle of radius 1 inside the square. pi is the ratio between the area of the circle and the area of the square.

    Now pick a few hundred thousand numbers inside the square. Count how many of them are inside the circle. Compute the ratio and you have a pretty good approximation of pi.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.