I'm a bit stuck calculating the value of π from the infinite series:
π = 4 – 4/3 + 4/5 – 4/7 + 4/9 – 4/11 + ...
The problem have to solve is "Print a table that shows the value of π approximated by computing the first 200,000 terms of this series. How many terms do you have to use before you first get a value that begins with 3.14159?"
I'm not sure if the condition that I'm using for finding this term is correct. Can someone tell me if it's right or not and if not what's the correct way to do this? I suspect it pertains to how Java rounds numbers.
package com.company;
public class Main {
public static void main(String[] args) {
double result = 0;
int j = 1;
int k = 1; //controls the if part for finding the term
int term = 0; //variable for term that we're looking for
for (int i = 1; i <= 200000; i += 1) {
if ((i % 2) != 0) {
result += (double) 4 / j; //positive part
j += 2;
}
else {
result -= (double) 4 / j; //negative part
j += 2;
}
if (k != 0) {
/* Attempts to detect when result == 3.14159 */
if (result > 3.14158 && result < 3.14160) {
term = i;
k = 0;
}
}
System.out.printf("%f\n", result);
}
System.out.println("Term at which pi has value 3.14159: " + term);
}
}