EN
Java - Math.PI property example
0 points
The Math.PI
property returns π number (3.141592653589793...
).
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
5
// ------------------------------------------------------
6
// Math.PI value priting:
7
8
System.out.println( Math.PI ); // 3.141592653589793
9
10
// ------------------------------------------------------
11
// Math.PI with circle:
12
13
final double radius = 5;
14
15
// 1. Circle surface area:
16
double area = Math.PI * Math.pow(radius, 2);
17
System.out.println( area ); // 78.53981633974483
18
19
// 2. Circle circumference:
20
double circumference = 2 * Math.PI * radius;
21
System.out.println( circumference ); // 31.41592653589793
22
}
23
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static final double PI = 3.14159265358979323846; 6 7 }
|
Result | π number (3.141592653589793... ). |
Description |
|
To calculate PI number Nilakantha series can be used.

xxxxxxxxxx
1
public class CustomMath {
2
3
static double computePi(int iterations) {
4
double approximation = 3;
5
double a = 2;
6
for (int i = 0; i < iterations; i++) {
7
approximation += 4 / (a * (++a) * (++a));
8
approximation -= 4 / (a * (++a) * (++a));
9
}
10
return approximation;
11
}
12
13
public static void main(String[] args) {
14
15
System.out.println( CustomMath.computePi( 1 )); // 3.1333333333333333
16
System.out.println( CustomMath.computePi( 2 )); // 3.1396825396825396
17
System.out.println( CustomMath.computePi( 5 )); // 3.1414067184965018
18
System.out.println( CustomMath.computePi( 10 )); // 3.141565734658547
19
System.out.println( CustomMath.computePi( 20 )); // 3.141589028940776
20
System.out.println( CustomMath.computePi( 50 )); // 3.1415924109719824
21
System.out.println( CustomMath.computePi( 100 )); // 3.141592622804848
22
System.out.println( CustomMath.computePi( 200 )); // 3.1415926497127264
23
System.out.println( CustomMath.computePi( 500 )); // 3.141592653340544
24
System.out.println( CustomMath.computePi( 1000 )); // 3.141592653558594
25
System.out.println( CustomMath.computePi( 2000 )); // 3.141592653585895
26
System.out.println( CustomMath.computePi( 5000 )); // 3.141592653589538
27
}
28
}