This code calculates an approximation of the mathematical constant π...
September 4, 2025 at 04:34 PM
This code calculates an approximation of the mathematical constant π (pi) using the Leibniz formula for π, which states:
[ \pi = 4 \cdot \left( 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \dots \right) ]
Explanation of the code:
int terms = 100000;
: Sets the number of terms to include in the approximation. More terms result in better accuracy.double sum = 0.0;
: Initializes the sum where the partial results of the formula will be stored.int i = 0;
: Initializes the counter to track the current term in the formula.double sign = 1.0;
: Keeps track of the alternating signs (+
and-
).- While loop (
while (i < terms) {...}
):- Calculates each term of the series:
sign / (2 * i + 1)
. - Adds the term to the running total
sum
. - Flips the sign (
+
to-
or-
to+
) usingsign = -sign
. - Increments the counter
i
to proceed to the next term.
- Calculates each term of the series:
- After the loop:
double piApprox = 4 * sum;
: Multiplies the final sum by 4 to approximate π.System.out.println(piApprox);
: Prints the computed value of π.
Simplified Code:
We can make the code shorter by combining the variable declarations and avoiding sign
explicitly:
int terms = 100000; // Number of terms
double sum = 0.0;
for (int i = 0; i < terms; i++) {
sum += (i % 2 == 0 ? 1.0 : -1.0) / (2 * i + 1); // Alternating signs
}
double piApprox = 4 * sum; // Compute approximation of pi
System.out.println(piApprox);
In this version:
- The
while
loop is replaced by afor
loop. - The alternating sign is calculated directly using
(i % 2 == 0 ? 1.0 : -1.0)
instead of manually flipping thesign
variable. This checks ifi
is even or odd to determine the sign.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node