C# Math.PI ConstantUse the Math.PI constant from the System namespace. PI equals 3.14159265358979.
Pi. In C# programs, pi is available in the Math.PI constant. Further, pi can be computed with an algorithm. But this is rarely needed.
C# field details. 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.
Example. 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
C# program that uses Math.PI
using System; class Program { static void Main() { double pi = Math.PI; Console.WriteLine(pi); } }
Example 2. 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.
Here The PI method is called. Then PI calls the F method and multiplies the final result by 2.
Also We calculate half of pi. The F method receives an integer that corresponds to "k" in Newton's formula.
Int, uint
And It proceeds until it has been called 60 times, which is an arbitrary limit I imposed.
Main Here these methods are called and the result is written to the screen up to 20 digits. The const Math.PI is also written.
C# program that computes pi
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
Newton. 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.
Info The result of the formula becomes increasingly accurate the longer you calculate it.
Summary. 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.
© 2007-2021 sam allen.
see site info on the changelog.