MSDN Archive Home
Help and FAQs
All Resource Updates
Change History (all pages)
Resource Page Description
This sample illustrates how to using .NET4 parallel extensions.
In the following set of exercises, you will implement an application that calculates Pi by using a geometric approximation. Initially, you will perform the calculation in a single-threaded manner; you will then change the code to divide the calculation into discrete operations and perform the calculation by using thread pool threads. Finally, you will change the code to use the Task Parallel Library to perform each operation as a parallel task. In the process, you will uncover some data synchronization issues that you must deal with.
The algorithm that you will implement calculates Pi based on some simple mathematics and statistical sampling.
If you draw a circle of radius r and then draw a square with sides that touch the circle, the sides of the square are 2 * r in length, as shown in Figure 1.
Figure 1. Circle and bounding square.
The area of the square, S, is calculated as follows:
S = (2 * r) * (2 * r)
This can be rearranged as:
S = 4 * r * r
You can further rearrange to give:
r * r = S / 4
The area of the circle, C, is calculated as follows:
C = Pi * r * r
Substituting for r*r and rearranging gives:
Pi = 4 * C / S
To calculate Pi, you must determine the value of the ratio C / S. This is where statistical sampling helps.
To do this, generate a set of random points that lie inside the square, and count how many of these points also fall inside the circle. If you have generated a sufficiently large and random sample, the ratio of points that lie inside the circle to the points that lie inside the square (and also in the circle) approximates the ratio of the areas of the two shapes, C / S. All you have to do is count them.
How do you determine whether a point lies inside the circle? To help visualize the solution, draw the square on a piece of graph paper with the center of the square at the origin, which is point (0, 0). You can then generates pairs of values, or coordinates, that lie inside the range (-r, -r) to (+r, +r). You can determine whether any set of coordinates (x, y) lie inside the circle by applying Pythagoras’ theorem to calculate the distance (d) of these coordinates from the origin. You can compute d as the square root of ((x * x) + (y * y)). If d is less than or equal to r, the radius of the circle, the coordinates (x, y) specify a point inside the circle, as shown in Figure 2.
Figure 2 Illustrating the distance of the point from the center of the circle.
Feb 27 2010 at 12:44 AM
, version 5
Sign in to add a comment
Using .NET4 Parallel E...
Sat Mar 13 2010 at 8:00 AM
More Tags ...
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Manage Your Profile
MSDN Flash Newsletter
© 2008 Microsoft Corporation. All rights reserved.