Book Image

The Modern C# Challenge

By : Rod Stephens
Book Image

The Modern C# Challenge

By: Rod Stephens

Overview of this book

C# is a multi-paradigm programming language. The Modern C# Challenge covers with aspects of the .NET Framework such as the Task Parallel Library (TPL) and CryptoAPI. It also encourages you to explore important programming trade-offs such as time versus space or simplicity. There may be many ways to solve a problem and there is often no single right way, but some solutions are definitely better than others. This book has combined these solutions to help you solve real-world problems with C#. In addition to describing programming trade-offs, The Modern C# Challenge will help you build a useful toolkit of techniques such as value caching, statistical analysis, and geometric algorithms. By the end of this book, you will have walked through challenges in C# and explored the .NET Framework in order to develop program logic for real-world applications.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Free Chapter
1
Mathematics
3
Dates and Times
4
Randomization
6
Files and Directories
7
Advanced C# and .NET Features
Index

Solutions


The following sections describe solutions to the preceding problems. You can download the example solutions to see additional details and to experiment with the programs athttps://github.com/PacktPublishing/The-Modern-CSharp-Challenge/tree/master/Chapter02.

 

20. 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...