Reputation: 27
I have to wright a function for Newtons approximation of Pi.
Newton calculated that Pi/(2* sqrt(2)) = 1+ 1/3 - 1/5 - 1/7 + 1/9 + 1/11 -...
public class newtonPi {
public static void main(String []args) {
int n = 10;
double piN = 0;
int sign = -1;
for(int i = 1; i < n; i+=2) {
System.out.println("i:"+i+" sign:"+sign);
piN += sign*(1.0/i);
sign *= -1;
}
System.out.println(piN*(2*Math.sqrt(2)));
}}
But with this approach, the sign changes everytime and not every other.
Thanks for the help :)
Upvotes: 0
Views: 397
Reputation: 425198
The pattern repeats every 8. Use the remainder operator %
(aka modulo):
sign = n % 8 > 4 ? -1 : 1;
Upvotes: 4
Reputation: 530
If I understood your question, you want to change the sign every two iterations, right? The problem is you're doing sign *= -1
on each iteration.
Try to use another variable in order to figure out if the sign must be inverted in the current iteration. Here is your code updated:
int sign = 1; // Start with positive
for(int i = 1,iteration = 0; i < n; i += 2,iteration++) {
System.out.println("i:" + i + " sign:" + sign);
piN += sign * (1.0 / i);
if(iteration % 2 != 0){
sign *= -1; // Change every 2 iterations, the odd ones
}
}
Upvotes: 3