2015-10-17 70 views
0

我正在计算正确的Monte Carlo Pi程序时遇到问题。 基本上,pi只在此刻才显示最多2个小数点,并且我觉得计算出错了,因为最接近的pi计算数字变得更高是2.98-3.04。蒙特卡洛Pi不准确

我的代码粘贴在下面。

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); 
    } 
} 
+0

你输入了什么? – dasblinkenlight

+0

@Sam问候。那么你会推荐我重新写这篇文章吗? – BelieveMe

+0

@dasblinkenlight我已经输入了“n”,所有数字从50到100,000不等,答案似乎并没有像实际的pi那样接近。 – BelieveMe

回答

1

这些调用

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

给你一个整数。但你需要doubles

x = rand.NextDouble() * 2 - 1; 
y = rand.NextDouble() * 2 - 1; 
+0

谢谢你现在的作品,没有意识到是这样的情况:)非常感谢我会选择答案,当它已经5分钟 – BelieveMe