I wanted to know how I can generate pi to the nth digit. I have a couple of basic ideas.
Math.PI
and increase the precision (if that's possible)So in short, either way, I would need to increase the precision of BigDecimal
depending on what the nth digit is. How would I go about increasing the precision of BigDecimal
to nth digit? Also, if there is a better and faster of doing this, can you please point me in the correct direction.
EDIT: I just want to generate PI. I don't want to use for calculations. and this is a question about how I can use BigDecimal to implement my ideas of generating PI.
Pi = SUMk=0toinfinity 16-k [ 4/(8k+1) – 2/(8k+4) – 1/(8k+5) – 1/(8k+6) ]. The reason this pi formula is so interesting is because it can be used to calculate the N-th digit of Pi (in base 16) without having to calculate all of the previous digits!
There are essentially 3 different methods to calculate pi to many decimals. One of the oldest is to use the power series expansion of atan(x) = x - x^3/3 + x^5/5 - ... together with formulas like pi = 16*atan(1/5) - 4*atan(1/239). This gives about 1.4 decimals per term.
PI” constant of the “java. It is a static double type constant that belongs to the Java Math class: public static final double PI = 3.14159265358979323846; Note: The “final” keyword is utilized for defining a constant that maintains its value and keeps it the same during the execution.
It is a mathematical constant that is defined as the circumference of a circle divided by its diameter. The value of a constant pi is approximately 3.14. Java provides built-in constant field of Pi that belong to java.
Math.PI
is of type double
. That means about 15 decimal digits of precision, and that is all the data you have; nothing will magically make additional digits of PI appear.BigDecimal
has arbitrary precision. setScale()
allows you to create BigDecimal
objects with as much precision as you want and most of the arithmetic methods will automatically increase precision as required, but of course the more precision, the slower all calculations will be.BigDecimal
, so you'll have to write your own.You need to use MathContext
to increase the precision of the BigDecimal
e.g.
MathContext mc = new MathContext(1000);
BigDecimal TWO = new BigDecimal(2, mc);
It's important that ALL the BigDecimal
s you use in your calculations use that MathContext
.
Heron's method should give you 1000 digits precision with only 10 iterations and a million digits with 20 iterations so it's certainly good enough.
Also, create all the constant BigDecimal
s like e.g. 26390
only once at the start of your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With