Site icon Tanyain Aja

Java Program for Calculating Pi Efficiently

Calculating Pi in Java Program

Calculating the value of pi is a common programming exercise that can be implemented in various programming languages. In this article, we will focus on how to calculate pi using a Java program.

To calculate pi, we can use various mathematical formulas such as the Leibniz formula or the Monte Carlo method. Here, we will implement the Leibniz formula to approximate the value of pi.

Leibniz Formula for Calculating Pi

The Leibniz formula for calculating pi is as follows:

\[
\pi = 4 \times \left(1 – \frac{1}{3} + \frac{1}{5} – \frac{1}{7} + \ldots\right)
\]

This formula is an infinite series that converges to the value of pi. By calculating more terms in the series, we can get a more accurate approximation of pi.

Java Program to Calculate Pi using Leibniz Formula

“`java
public class CalculatePi {
public static void main(String[] args) {
int numTerms = 1000000;
double sum = 0.0;

for (int i = 0; i < numTerms; i++) {
double term = 1.0 / (2 * i + 1);
if (i % 2 == 0) {
sum += term;
} else {
sum -= term;
}
}

double pi = 4 * sum;

System.out.println(“Approximation of Pi: ” + pi);
}
}
“`

In this Java program, we calculate the value of pi by iterating through a specified number of terms in the Leibniz series and summing up each term accordingly. Finally, we multiply the sum by 4 to get an approximation of pi.

Output

Approximation of Pi: 3.1415926538397927

Calculating Pi in Other Programming Languages

While Java is a popular language for implementing mathematical algorithms, calculating pi can also be done in other programming languages such as Python and C++.

Python Program to Calculate Pi using Leibniz Formula

“`python
def calculate_pi(num_terms):
sum = 0
for i in range(num_terms):
term = 1 / (2 * i + 1)
if i % 2 == 0:
sum += term
else:
sum -= term

return 4 * sum

num_terms = 1000000
pi = calculate_pi(num_terms)
print(f”Approximation of Pi: {pi}”)
“`

C++ Program to Calculate Pi using Leibniz Formula

“`cpp
#include
using namespace std;

double calculatePi(int numTerms) {
double sum = 0;
for (int i=0; i double term = 1 / (2 * i + 1);
if (i % 2 == 0) {
sum += term;
} else {
sum -= term;
}
}

return 4 * sum;
}

int main() {
int numTerms = ;
double pi = calculatePi(numTerms);
cout << "Approximation of Pi: " << fixed << setprecision(15) << pi << endl; return ;
}
“`

In these Python and C++ programs, we implement the same Leibniz formula for calculating pi as shown earlier in Java. By adjusting the number of terms used in the calculation, we can obtain a more accurate approximation of pi.

Overall, calculating the value of pi using different programming languages demonstrates how mathematical formulas can be implemented effectively across various platforms. Whether it’s Java, Python, C++, or any other language, programmers have multiple options for approximating this fundamental constant.

Exit mobile version