Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BigDecimal to print Pi

I'm tring to use BigDecimal to print Pi, but it turns out it's not accurate

    BigDecimal d = new BigDecimal(Math.PI); 
    System.out.println(d); 

The above answer gives me "3.141592653589793115997963468544185161590576171875" but the digits after "3.141592653589793" is incorrect

how this is happenning ? and can i use bigdecimal to print PI ?

like image 436
YuanZheng Hu Avatar asked Dec 06 '25 04:12

YuanZheng Hu


1 Answers

From Javadoc for Math.PI:

PI

public static final double PI

The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

This is roughly (when printed as decimal expansion):

3.141592653589793

It's just a fixed sequence of 64 bits that represents an approximation of Pi, it is a hard-coded constant that is saved in the JAR of the standard library. This 64-bit sequence does not contain an algorithm for computing an arbitrary number of Pi digits.

The numbers that you see after the 15-th place are more or less pseudo-random garbage. Wrapping it into BigDecimal doesn't make it any more precise.

like image 179
Andrey Tyukin Avatar answered Dec 07 '25 20:12

Andrey Tyukin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!