In C# programs, pi is available in the Math.PI
constant. Further, pi can be computed with an algorithm. But this is rarely needed.
Using pi in your program is not your main goal here, but finding ways to acquire its value is useful. Here we look at ways to get pi.
Here we access the double
PI. Include the System
namespace and then call the Math.PI
composite name. Math.PI
here returns a double
equal to 3.14.
using System; class Program { static void Main() { double pi = Math.PI; Console.WriteLine(pi); } }3.14159265358979
Here we calculate pi. This program is basically never useful in a real-world program. It has no advantage over using Math.PI
. It shows the algorithm implementation.
const
Math.PI
is also written.using System; class Program { static void Main() { // Get PI from methods shown here double d = PI(); Console.WriteLine("{0:N20}", d); // Get PI from the .NET Math class constant double d2 = Math.PI; Console.WriteLine("{0:N20}", d2); } static double PI() { // Returns PI return 2 * F(1); } static double F(int i) { // Receives the call number if (i > 60) { // Stop after 60 calls return i; } else { // Return the running total with the new fraction added return 1 + (i / (1 + (2.0 * i))) * F(i + 1); } } }3.14159265358979000000 3.14159265358979000000
Isaac Newton spent a long time calculating pi to 15 decimal places. You can see that the equation defines half of pi as the sum of a fraction, expanded from 0 to infinity.
We used the Math.PI
constant. We then saw a way to calculate the value of pi. We learned about double
precision and the string
format patterns for decimal places.