原创 随机算法求圆周率演示程序源代码收藏

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

        }


    }
}

发表于 @ 2006年09月19日 22:08:00|评论(loading...)

 | 旧一篇: bp网络算法对y=0.4sin(2*PI*x)+0.5的拟合

用户操作
[即时聊天] [发私信] [加为好友]
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
文章分类
收藏
    存档
    软件项目交易
    Csdn Blog version 3.1a
    Copyright © 海