# Thread: Errors in digits of calculating pi

1. Member
Join Date
Oct 2010
Posts
4
Rep Power
0

## Errors in digits of calculating pi

This class runs, compiles and such, but its output is a 'bit' off. It gives the value of 3.1583289............

My theory is that its because transfer of doubles to BigDecimal. I did this because it makes it easier because you can just use operators simplifying the code a bit. I used the method valueOf to possibly fix it, but there was no change in the output.

If that's the problem is there any way around it with minimal changes or do I have to convert everything to BigDecimal in order to get accurate output?Looking for some advice as to if the problem is what I think it is or something else and help on fixing it.

Java Code:
```import java.math.BigDecimal;

public class pi
{
private long nums = 0;
private String out;
private String test1; //*******************************
private String test2; // Temporary strings for testing
private String test3; //********************************

BigDecimal pi = new BigDecimal(0); //Final Answer
BigDecimal arc1 = new BigDecimal(0); //Arctan of 1/5
BigDecimal arc2 = new BigDecimal(0);//Arctan of 1/239
BigDecimal FOUR = new BigDecimal("4"); //Constant used to multiply

public pi(long run) //Gets input for user for number of iterations of program
{
nums = run;
}

private void calcArc1 () //1/5
{
BigDecimal temp = new BigDecimal("0");
double arctan = 0;

for (long count = 0; count <= nums; count++)
{
arctan = (((Math.pow(-1,count))*(Math.pow(.2,2*count+1)))/(2*count+1));

temp = temp.valueOf(arctan);
}

arc1 = arc1.multiply(FOUR);

}

private void calcArc2 () //1/239
{
BigDecimal temp = new BigDecimal("0");
double arctan = 0;

for (long count = 0; count <= nums; count++)
{
arctan = (((Math.pow(-1,count))*(Math.pow(1/239,2*count+1)))/(2*count+1));

temp = temp.valueOf(arctan);

}

}

public void calcPi ()
{

calcArc2();
calcArc1();
pi = arc1.subtract(arc2);
pi = pi.multiply(FOUR);

}
public String toString()
{

out = "Pi is " + pi;

return out;
}
}```
And the code that runs it

Java Code:
```import java.util.Scanner;

public class picalc
{
public static void main (String [] args)
{
long iterations = 0;
Scanner scan = new Scanner(System.in);
iterations = scan.nextLong();

}```

2. You are doing all your calculations in type double; only the intermediate results are cast to a BigDecimal type. See this page how to do all calculations in type BigDecimal.

kind regards,

Jos

Hmm.......

Note: Please ignore this post as it has been remedied by a moderator.
Last edited by Zack; 12-26-2010 at 01:52 AM.

4. Originally Posted by Zack

Hmm.......
Agree. Deleted.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•