Home
Map
Math.PI Use (Constant)Use the Math.PI constant from the System namespace. PI equals 3.14159265358979.
C#
This page was last reviewed on Nov 17, 2021.
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, uint
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2021 (edit link).
Home
Changes
© 2007-2024 Sam Allen.