2007-08-23
随机算法求圆周率 - [Algorithms]
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://conoon.blogbus.com/logs/7872522.html
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void count(Random rand)
{
Console.Write("请输入运算的次数:");
Int32 N = 0;
Int32 K = 0;
try
{
string strinput = Console.ReadLine();
Int32 M = Convert.ToInt32(strinput);
for (Int32 i = 0; i < M; i++)
{
double x = rand.NextDouble();
double y = rand.NextDouble();
if (x * x + y * y <= 1)
{
N++;
if (x + y >= 1) K++;
}
}
double result1 = (double)4 * N / M;
Int32 J = M - N;
double result2=(double)(4*K+2*J)/(K+J);
double wucha1=result1-System.Math.PI;
double wucha2 = result2 -System.Math.PI;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("经过{0}次随机事件后,算法1圆周率为{1},误差为{2}.", M, result1,wucha1);
Console.WriteLine("经过{0}次随机事件后,算法2圆周率为{1},误差为{2}.\n", M, result2,wucha2 );
Console.ForegroundColor = ConsoleColor.White;
}
catch {
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("输入有误,");
}
}
static void Main(string[] args)
{
Console.WriteLine("****************************");
Console.WriteLine("随机算法求圆周率演示程序\n");
Console.WriteLine("****************************\n");
Console.ForegroundColor = ConsoleColor.White;
Random rand = new Random();
while (true)
{
count(rand);
}
}
}
}
收藏到:Del.icio.us





