Reputation:
We got an assignment where we have to calculate the value of pi using the formula pi/4=1-1/3+1/5-1/7+1/9-1/11...
(using 100
terms) but it doesn't seem to run the while-loop for some reason. We're students who have no prior experience of writing code and are just starting.
double pi = 1;
int count = 0;
int n = 3;
while (count < 100) {
if ((count&1) == 0) {
pi = pi - 1 / n;
} else {
pi = pi + 1 / n;
}
n = n + 2;
count++;
}
out.print(pi*4); //why is it printing out pi=1?????
Upvotes: 1
Views: 201
Reputation: 1508
The problem is you do not type cast. pi
is double but 1/n
returns int, since both the denominator and numerator are integers. This happens in JAVA. Basically, every time, 1/n
which is actually fractional, returns 0
(int) for every n > 1
due to lack of type casting. So pi
's value is always 1 and in the end pi*4
displays 4.0. So you have to convert (cast) the numerator or the denominator as fractional (double) to make 1/n fractional.
To solve the problem, change the statements
pi = pi + 1 / n;
pi = pi - 1 / n;
to
pi = pi + 1.0 / (double) n;
pi = pi - 1.0 / (double) n;
This displays the output as 3.1514934010709914.
Upvotes: 7