1. Member
Join Date
Mar 2012
Posts
3
Rep Power
0

Java PI program issue

Hi all, im new here and new to java.

I have wrote this program for my hw assignment but it seems to only be accurate to the nth place after the decimal.
My instructor has given me this answer

Appoximate value of pi is: 3.1415826535897198

and i get:

Appoximate value of pi is: 3.1415726535897814

Here is my program. Hope this is how i am suppose to post here:

Java Code:
```//this program finds the aprox. value of pi from a user number

import java.util.Scanner;

public class Pi
{
public static void main (String[] args)
{
//create a scanner
Scanner keyboard = new Scanner(System.in);

int user; //user number
double sum = 0;      //sum of fractions
double fraction; //decimal value
int i;     //loop variable
double sign = 1;   // alt. signs

user = keyboard.nextInt();   //asign userNum a value

for (i = 1; i <= user; i+=2)     //loop parameters
{
fraction = 1.0/i;      //gets fractions by using i as denominator
sum = sum + sign * fraction;  //adds fractions to sum
sign = sign * (-1);    //changes sign of fraction
}

System.out.print("Appoximate value of pi is: " + sum * 4);   //display answer

}

}```
Anyone have an idea on how to fix this issue?

Last edited by Darin; 03-14-2012 at 11:23 PM.

2. Re: Java PI program issue

Can you post the algorithm or show the series that you are using to do the computation?

Why are you using a double to control the number of loop iterations?

Change the coloring of the post. The off yellow is unreadable.

3. Re: Java PI program issue

That series has a very, very slow convergence; see what happens if you add 1,000,000 terms or so. Do you get a better approximation? b.t.w. your code seems to look correct to me (I didn't give it a very close look, but note that the value of 'user' isn't the number of terms added).

kind regards,

Jos

4. Member
Join Date
Mar 2012
Posts
3
Rep Power
0

Re: Java PI program issue

Sorry JoshAH, this is the best i know how to do.

Norm,

I fixed the issues you have addressed with no avail. It still show different numbers at the end.

Can you post the algorithm or show the series that you are using to do the computation?
Im not sure what you mean by this. I have not yet learned about algorithms? But ill try to explain, I used the for loop to count all demonimators, then used the sum; fraction; and sign to perform the calculations.

pi = 4(1-1/3+1/5-1/7+1/9-1/11 ... ) and do on.
Last edited by Darin; 03-14-2012 at 11:24 PM.

5. Re: Java PI program issue

What value do you get if you loop 200M times

6. Re: Java PI program issue

You must have a very slow computer to have taken so long.

7. Member
Join Date
Mar 2012
Posts
3
Rep Power
0

Re: Java PI program issue

Sorry, ill be more prompt next time.