Home
C#
Math.PI Use (Constant)
Updated Nov 17, 2021
Dot Net Perls
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.
Math
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.
System
using System; class Program { static void Main() { double pi = Math.PI; Console.WriteLine(pi); } }
3.14159265358979
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.
Multiply
Divide
int
And It proceeds until it has been called 60 times, which is an arbitrary limit I imposed.
Detail Here these methods are called and the result is written to the screen up to 20 digits. The const Math.PI is also written.
Console.WriteLine
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2021 (edit link).
Home
Changes
© 2007-2025 Sam Allen