0

I am having trouble with my Monte Carlo Pi program calculating properly. Basically, pi is only displaying up to 2 decimal points only at the moment, and I feel the calculation has gone wrong somewhere as the closest pi calculation as number gets higher is 2.98-3.04.

My code is pasted below.

static void Main(string[] args)
{
    double n;
    double count;
    double c = 0.0;
    double x = 0.0, y = 0.0;
    double pi;
    string input;

    Console.WriteLine("Please input a number of dots for Monte Carlo to calculate pi.");
    input = Console.ReadLine();
    n = double.Parse(input);

    Random rand = new Random();


    for (int i = 1; i < n; i++ )
    {
        x = rand.Next(-1, 1);
        y = rand.Next(-1, 1);

        if (((x * x) + (y * y) <= 1))
            c++;
        pi = 4.0 * ( c / i );
        Console.WriteLine("pi: {0,-10:0.00} Dots in square: {1,-15:0} Dots in circle: {2,-20:0}", pi, i, c);
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
BelieveMe
  • 69
  • 1
  • 1
  • 7

2 Answers2

1

These calls

x = rand.Next(-1, 1);
y = rand.Next(-1, 1);

give you an integer. But you need doubles:

x = rand.NextDouble() * 2 - 1;
y = rand.NextDouble() * 2 - 1;
Nico Schertler
  • 32,049
  • 4
  • 39
  • 70
  • thankyou it works now, didn't realise that was the case :) thanks a lot I will select the answer when it has been 5minutes – BelieveMe Oct 17 '15 at 11:42
0

The random numbers should be generated between 0 and 1 and not -1 and 1. Used this fixed version of your code as "mysterious code" for students.

using System;

namespace mysCode
{
    class Program
    {
        static double euclideanDistance(double x1, double y1, double x2, double y2)
        {
            double dX = x2 - x1;
            double dY = y2 - y1;
            return Math.Sqrt(dX * dX + dY * dY);
        }

        static void Main(string[] args)
        {
            double n;            
            double c = 0.0;
            double x = 0.0, y = 0.0;
            double result;
            string input;
            Console.WriteLine("Quick, pick an integer");
            input = Console.ReadLine();
            n = double.Parse(input);
            Random rand = new Random();
            for (int i = 1; i <= n; i++)
            {
                x = rand.NextDouble();
                y = rand.NextDouble();
                if (euclideanDistance(x, y, 0, 0) <= 1)
                    c++;
                result = 4.0 * (c / i);                
                Console.WriteLine("Result: " + result);
            }
            Console.ReadKey();
        }

    }
}

It coverages very slowly, I get 3.14152314152314 after 1M iterations.

Guy s
  • 1,586
  • 3
  • 20
  • 27