0

I'm trying to calculate PI with some algorithms, but the main thing is to display it with precision of 30. I tried to output a string with format etc. But it seems that maximum precision of double is 15. Is there any class or some method to help me with this ?

I've already tried:

public class Challenge6PI {

    public static void main(String[] args){

        System.out.format( "%.30f",
                Math.log(Math.pow(640320, 3) + 744) / Math.sqrt(163));
    }
}
ashur
  • 4,177
  • 14
  • 53
  • 85

4 Answers4

3

While the JDK has BigDecimal, unfortunately you have no .sqrt() on it.

Which means your best bet is to use apfloat:

final Apfloat f1 = new Apfloat(640320);
final Apfloat f2 = ApfloatMath.pow(f1, 3L);
final Apfloat f3 = f2.add(new Apfloat(744));
final Apfloat f4 = ApfloatMath.sqrt(new Apfloat(163), 1000L);
final Apfloat ret = ApfloatMath.log(f3.divide(f4));

System.out.println(ApfloatMath.round(ret, 30L, RoundingMode.HALF_DOWN));

You have a shorter way for pi, though ;)

System.out.println(ApfloatMath.pi(30L));
fge
  • 119,121
  • 33
  • 254
  • 329
  • Thanks, I will try with `apfloat`, but I've also tried with `BigDecimal` which gave me theoretically nearly exact PI number with precision of 30. But some numbers are not equivalent when I compared it with http://3.141592653589793238462643383279502884197169399375105820974944592.com/index3141.html , what I've got is `3.141592652589793238462643383529`, which is strange because most of numbers are correct and some in the middle differ. – ashur Jun 16 '13 at 12:13
1

Take a look at the BigDecimal class! http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html

faffaffaff
  • 3,429
  • 16
  • 27
1

I guess Float does not supports that much precision. You may use BigDecimal for that.

Ankit Zalani
  • 3,068
  • 5
  • 27
  • 47
0

double doesn't have that much precision. Have a look at how the double type is implemented. For arbitrary precision have a look at BigDecimal

For example:

BigDecimal bd = new BigDecimal(22.0/7.0);
df.setMaximumFractionDigits(30);
System.out.println(df.format(bd));
squib
  • 1