I'm trying to make a program that calculates PI using the following algorithm:
PI = 4 x (1 - 1/3 + 1/5 - 1/7 + 1/9 ....) etc.
I don't understand how the operator placement is affecting the variable.
The outcome produced on the first iteration of the loop makes sense, but then it seems to reset to initialised value and ignore the assignment operators the second time through. Repeating this outcome 1, then outcome 2, then outcome 1, outcome 2, and so forth...
I tried looking in this book called "Java: How to Program (Early Objects), 11th Edition" and in chapter four they went over operators but I could see that they didn't cover the conditions within a loop.
double k = 1.0, j = 1.0;
double sum = 0, PI = 0;
while((Math.abs(PI-Math.PI)>0.000001)){
sum += k/j;
j = j + 2;
k=-k;
PI = 4 * sum;
System.out.println(k);
}
I changed the conditions of the while loop to run 4 times and print k. I expected the first printing of the variable 'k' to be -1.0. It is, but the second printing of k (second looping of while loop) is 1.0. The third is -1.0, then 4th is 1.0, and so forth...
I don't understand why it isn't -1.0 on all iterations, because with java assignment operators, as far as I know, if the left operator is '=' and the right operator is an incremental or decremental symbol, then the result should always be that the variable k will always = -k.
k == -1.0and you're doing-kon it? Or more precisely, what is-(-1.0)?k = -kin every iteration just switches the sign.