1. Monte Carlo π

The following code uses a Monte Carlo algorithm to estimate π:

// Use Monte Carlo simulation to estimate pi.private double MonteCarloPi(long numPoints){    Random rand = new Random();    // Make a bitmap to show points.    int wid = pointsPictureBox.ClientSize.Width;    int hgt = pointsPictureBox.ClientSize.Height;    Bitmap bm = new Bitmap(wid, hgt);    using (Graphics gr = Graphics.FromImage(bm))    {        gr.Clear(Color.White);        gr.DrawEllipse(Pens.Black, 0, 0, wid - 1, hgt - 1);    }    // Make the random points.    int numHits = 0;    for (int i = 0; i < numPoints; i++)    {        // Make a random point 0 <= x < 1.        double x = rand.NextDouble();        double y = rand.NextDouble();        // See how far the point is from (0.5, 0.5).        double dx = x - 0.5;        double dy = y - 0.5; if (dx ...

Get Improving your C# Skills now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.