如何使用蒙特卡罗方法计算pi [英] How do I calculate pi using monte carlo method
本文介绍了如何使用蒙特卡罗方法计算pi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输出应列表为列出n,c和Pi的每个估计值的Pi值,直到用户在运行时输入的选定点数。例如,如果用户输入500,则应显示500行。
我尝试过:
Console.Write( 请输入随机数编号:);
string input = Console.ReadLine();
n = double .Parse(输入);
if ((n< 1 )||(n> 500 ))
Console.WriteLine( 错误!数字应在1到500之间!
+ 请再试一次 跨度>);
else
while (n< 500 )
{
Console.Write( N + n);
n ++;
}
{
int x = 1 ;
double y = 1 ;
c = x * x + y * y;
c ++;
}
{
Pi = 4 * c / n;
Pi ++;
Console.WriteLine( N:{0},n);
Console.WriteLine( C:{0},c);
Console.WriteLine( Pi:{0},Pi);
}
解决方案
嗯。
您希望该代码做什么?
你从用户那里读了一个随机数 - 这是一个奇怪的想法 - 如果它超出限制(你没有告诉他)你打印一条消息,但继续使用无论如何...
否则,你把这个值的所有数字都写到500以上,并继续。
无论你之前打印什么,你设置c
通过一个复杂的方法得到三个,然后假设pi是0.024,加一个,然后打印
N: 500
C: 3
Pi: 1 。 024我知道这可能是你的功课,但是你需要扔掉它,坐下来,并试着弄清楚你应该在这里做什么 - 因为这甚至不像你老师问的那样对于! :笑:
The output should be tabulated to list n, c and the Pi value for each estimate of Pi up to a chosen number of points input by the user at run time. If the user input 500 for example, there should be 500 rows displayed.
What I have tried:
Console.Write("Please enter a Random Number: ");
string input = Console.ReadLine();
n = double.Parse(input);
if ((n < 1) || (n > 500))
Console.WriteLine("Error!The number should be between 1 and 500!"
+ "Please try again");
else
while (n < 500)
{
Console.Write("N" + n);
n++;
}
{
int x = 1;
double y = 1;
c = x * x + y * y;
c++;
}
{
Pi = 4 * c / n;
Pi++;
Console.WriteLine("N : {0}", n);
Console.WriteLine("C: {0}", c);
Console.WriteLine("Pi: {0} ", Pi);
}
解决方案
Um.
What do you expect that code to do?
You read a "random number" from the user - which is a strange idea to start with - and if it's outside the limits (that you didn't tell him) you print a message, but continue to use it anyway...
Otherwise, you write all the numbers from that value up to 500 inclusive and continue anyway.
Regardless of what you printed earlier, you setc
to three by a convoluted method, and then assume that pi is 0.024, add one to it, and print
N : 500 C : 3 Pi: 1.024I know this is probably your homework, but you need to throw that away, sit down, and try to work out exactly what you are supposed to be doing here - because that isn't even close to what you teacher asked for! :laugh:
这篇关于如何使用蒙特卡罗方法计算pi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文