Monte Carlo 数值积分
var amount = 0.0d; var hitTheTargetCount = 0.0d; var M = 2.0d; var rnd=new Random(); for (int i = 0; i < 1000; i++) { var x = rnd.NextDouble() * Math.PI; var y = rnd.NextDouble() * M; //Console.WriteLine("x:{0},y:{1}", x, y); if (y <= Math.Sin(x)) { hitTheTargetCount++; } amount++; } var s = (hitTheTargetCount / amount) * M * Math.PI; Console.WriteLine(s);
以上代码针对 sin(x) 0-pi 进行积分
积分int( sqrt(1-x^2),0,1)
private void button1_Click(object sender, EventArgs e) { var amount = 0.0d; var hitTheTargetCount = 0.0d; var M = 1.0d; var rnd=new Random(); for (int i = 0; i < 10000; i++) { var x = rnd.NextDouble() * M; var y = rnd.NextDouble() * M; //Console.WriteLine("x:{0},y:{1}", x, y); if (y <= Math.Sqrt(1-Math.Pow(x,2))) { hitTheTargetCount++; } amount++; } var s = (hitTheTargetCount / amount) * M * M; Console.WriteLine(s * 4); } private void button2_Click(object sender, EventArgs e) { Func<double, double> func = (x) => { return (Math.Sqrt( 1 - Math.Pow(x, 2))); }; var n = 10000; double h = 1.0d / n; double sumx = 0; double sum = func(0.0); for (int i = 1; i < n; i++) { sumx += h; var factor = ((i % 2) == 1) ? 4 : 2; //Console.WriteLine(i +":" + factor +"," + sumx); sum += factor * func(sumx); } sum += func(1); var v = 4 * (sum * h) / 3; Console.WriteLine(v); }