Search code examples
c#classrandommethodsmontecarlo

Variables in methods in C#


The following code is for a class homework problem. The goal of the program is to estimate the value of Pi using simulated dart throws at a circle within a square. The idea is to use 2 random numbers to calculate if a dart hits inside the circle. If (x - 0.5)^2 + (y - 0.5)^2 < 0.25 the dart lands within the circle. the (number of "hits" / number of misses) * 4 is an approximate value of Pi. The more darts thrown the closer the estimate. The following code generates the random numbers and seems to calculate the "throwLocation", but it always outputs an estimate of 0. I believe this may be because the hits variable is not being incremented correctly. Since hits is always = 0 the estimate will be 0 since 0 / the number of throws is always zero. Is there a problem with the methods in this code? Or is there another issue? Thanks

namespace hw_6_17
{
class PiWithDarts
{
    public int throwDarts;
    public int hits = 0;
    public double piEst;

    //increments the number of thrown darts
    public void DartThrown()
    {

        throwDarts++;
    }

    //calculates and tracks hits
    public void Hits()
    {
        double xValue;
        double yValue;
        double throwLocation;
        Random r = new Random();

        xValue = r.NextDouble();
        yValue = r.NextDouble();

        Console.WriteLine("{0}", xValue);
        Console.WriteLine("{0}", yValue);
        throwLocation = ((xValue - 0.5) * (xValue - 0.5)) + ((yValue - 0.5) * (yValue - 0.5));
        Console.WriteLine("throw, {0}", throwLocation);

        if (throwLocation < .25)
        {
            hits++;

        }

    }

    //estimate pi based on number of hits
    public void CalcPi()
    {
        piEst = (hits / throwDarts) * 4;
        Console.WriteLine("Based off the darts thrown, Pi is approximately {0}.", piEst);
        Console.ReadLine();
    }


    static void Main(string[] args)
    {
        int numToThrow;
        int count = 0;
        PiWithDarts NewRound = new PiWithDarts();


        Console.WriteLine("How many darts will be thrown?");
        numToThrow = int.Parse(Console.ReadLine());

        while(count < numToThrow)
        {
            NewRound.DartThrown();
            NewRound.Hits();
            count++;
        }

        NewRound.CalcPi();
    }
}
}

Solution

  • the problem is throwDarts and hits are of type int
    you need to cast those int variables to double or float to get the result correctly
    you can use this

    public void CalcPi()
        {
            piEst = ((double)hits / (double)throwDarts) * 4;
            Console.WriteLine("Based off the darts thrown, Pi is approximately {0}.", piEst);
            Console.ReadLine();
        }