Leibniz series Loop not converging

Try this.

for (int i=1; i < n; i++) {
    double calculations = Math.pow(-1,i + 1) / (2 * (i-1) + 1);
    sum += calculations;
}
System.out.println(4*sum);

  • First, the first denominator must be 1 so 2*(i-1) + 1 = 0 + 1 = 1.
  • Second, remember that the series computes pi/4 so you need to mutiply by 4.

Here is a suggestion. Instead of doing the Math.pow overhead, just use a ternery operator (?:)to see if i is even or odd and change the sign accordingly.

  double calculations = ((i % 2) == 0 ? -1. : 1.) / (2.*(i-1)+1);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top