2. Newton's π

The following code implements Newton's method for calculating π:

// Use Newton's formula to calculate pi.
private double NewtonPi(int numTerms)
{
double total = 0;
for (int i = 0; i < numTerms; i++)
{
total +=
Factorial(2 * i) /
Math.Pow(2, 4 * i + 1) /
(Factorial(i) * Factorial(i)) /
(2 * i + 1);
}

double result = 6 * total;
Debug.Assert(!double.IsInfinity(result));
return result;
}

This method simply loops over the desired number of terms, calculates the appropriate term values, and adds them to the result.

To allow the program to work with larger values, it uses the following Factorial method:

// Return number!
private double Factorial(int number)
{
double total = 1;
for (int i = 2; i <= number; i++) total *= i;
return total;
}

This is a normal factorial, except it stores its total in a double variable, which can hold larger values than a long variable can.

The value 355/113 is approximately 3.1415929, which is remarkably close to π. Newton's method converges very quickly on values close to π, only needing nine terms before it is more accurate than 355/113.

This method runs into problems when numTerms is greater than 86. In that case, the value Factorial(2 * i) is too big to fit in a double variable. Because the problem occurs in a double variable instead of an integer, a checked block won't detect the problem.

As is the case with integers, C# doesn't notify you if the value doesn't fit in a double variable. Instead, it sets the variable equal to one of the special value, values double.Infinity or double.NegativeInfinity. The NewtonPi method uses a Debug.Assert statement to see if this happened.

The Debug class is defined in the System.Diagnostics namespace, so the program includes the directive using System.Diagnostics to make using that class easier.

The lesson to be learned here is that you should use the double.IsInfinity method to check double variables for overflow to infinity or negative infinity if that might be an issue.

Some double calculations, such as total = Math.Sqrt(-1), may result in the special value double.NaN, which stands for Not a Number. You can use the double.IsNaN method to check for that situation.

Download the NewtonPi example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.244.154