How to Calculate PI

Had a job interview test to calculate PI using the built in random number generator in Java. This is the same result using C#. Assume this method is a member of a class…since functions cannot stand on their own in Java or C#. (And, yeah, it would throw an exception if you passed in zero for numPoints.)

public static double CalcPi(uint numPoints)
    double count = 0;
    Random rand = new Random();
    for (uint i = 0; i < numPoints; ++i)
        if (Math.Sqrt(Math.Pow(rand.NextDouble(), 2) + Math.Pow(rand.NextDouble(), 2)) <= 1.0)

    return count * 4.0 / numPoints;
This entry was posted in Uncategorized. Bookmark the permalink.