-3

I'm just starting out with programming and need to do an assignment for class where I approximate pi using the first 8 terms in the sequence. I need to do this by creating a variable 'nextTerm' with initial value 1, variable 'denominator' with initial value 1, and variable 'series' with initial value 0. I get the first term when I run it, but then it only shows a line of zeros. I honestly have no clue what I'm doing.

public class ApproxPI
{
    public static void main(String[] args)
    {
        int nextTerm = 1;
        int denominator = 1;
        int series = 0;

        for (int denominator = 1; denominator <= 8; denominator++) {
            series = ((-1 * ((-1 * nextTerm) / denominator)) * 4);
            System.out.println("Pi is approximately" + series);
        }   
    }
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Puck
  • 1
  • 1

2 Answers2

0

Why don't you update nextTerm ever? It will always equal 1, an int, with the code you show. So your loop will be equivalent to:

series = ( -1 * (( -1 * 1 ) / denominator )) / 4;

or equivalently

series = ( -1 * ( -1 / denominator )) / 4;

or

series = ( 1 / denominator ) / 4;

On each pass, because it is int arithmetic which throws away fractions:

( 1 / 1 ) / 4 => 1 / 4 => 0
( 1 / 2 ) / 4 => 0 / 4 => 0
( 1 / 3 ) / 4 => 0 / 4 => 0
. . .
( 1 / 8 ) / 4 => 0 / 4 => 0

Don't use int arithmetic. Don't use float, either, use double, for both the variables and the literals. You will never be able to calculate π using only int values.

Also, even if you got that right, your output would look something like:

Pi is approximately3
Pi is approximately1
Pi is approximately4
Pi is approximately1
Pi is approximately5
. . .

which might not be exactly what you intend.

This kind of manual walkthrough of the algorithm I was taught to call a "pencil test". Follow the logic precisely with (virtual) pencil and paper to see what it really does, not what you think it does.

You don't need to declare and initialize denominator twice. You do need to fix the use of nextTerm.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
-1

I don't know method this is to calculate PI but you surely should initialize your float and 1.0 instead of 1. e.x

float nextTerm = 1.0; instead of int nextTerm = 1.0.

Do this for every variable to ensure the functionality

hesyar
  • 467
  • 1
  • 5
  • 12
  • This explanation lacked the explanation of why `int` calculation didn't work, and should have recommended `double` rather than `float`. It also missed the misuse of `nextTerm`. – Lew Bloch Jan 18 '17 at 22:01