EN
C# / .NET - Math.PI property example
0
points
The Math.PI
property returns π number (3.141592653589793...
).
using System;
class Program
{
static void Main(string[] args)
{
// ------------------------------------------------------
// Math.PI value priting:
Console.WriteLine(Math.PI); // 3.141592653589793
// ------------------------------------------------------
// Math.PI with circle:
double radius = 5;
// 1. Circle surface area:
double area = Math.PI * Math.Pow(radius, 2);
Console.WriteLine(area); // 78.53981633974483
// 2. Circle circumference:
double circumference = 2 * Math.PI * radius;
Console.WriteLine(circumference); // 31.41592653589793
}
}
1. Documentation
Syntax |
|
Result | π number (3.141592653589793... ). |
Description |
|
2. Nilakantha series example
To calculate PI number Nilakantha series can be used.
using System;
public class Program
{
static double ComputePi(int iterations)
{
double approximation = 3;
double a = 2;
for (int i = 0; i < iterations; i++)
{
approximation += 4 / (a * (++a) * (++a));
approximation -= 4 / (a * (++a) * (++a));
}
return approximation;
}
public static void Main(string[] args)
{
Console.WriteLine( ComputePi( 1 )); // 3.1333333333333333
Console.WriteLine( ComputePi( 2 )); // 3.1396825396825396
Console.WriteLine( ComputePi( 5 )); // 3.1414067184965018
Console.WriteLine( ComputePi( 10 )); // 3.141565734658547
Console.WriteLine( ComputePi( 20 )); // 3.141589028940776
Console.WriteLine( ComputePi( 50 )); // 3.1415924109719824
Console.WriteLine( ComputePi( 100 )); // 3.141592622804848
Console.WriteLine( ComputePi( 200 )); // 3.1415926497127264
Console.WriteLine( ComputePi( 500 )); // 3.141592653340544
Console.WriteLine( ComputePi( 1000 )); // 3.141592653558594
Console.WriteLine( ComputePi( 2000 )); // 3.141592653585895
Console.WriteLine( ComputePi( 5000 )); // 3.141592653589538
}
}