简体   繁体   English

Java:显示浮点数,精度为30

[英]Java: Display float with precision of 30

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 ? 我正在尝试使用某些算法来计算PI,但是主要的事情是以30的精度显示它。我试图以format等输出字符串。但是似乎double最大精度是15。是否有任何类或有什么方法可以帮助我吗?

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));
    }
}

While the JDK has BigDecimal , unfortunately you have no .sqrt() on it. 尽管JDK具有BigDecimal ,但是不幸的是您没有.sqrt()

Which means your best bet is to use apfloat : 这意味着最好的选择是使用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 ;) 不过,您使用pi的方法更短;)

System.out.println(ApfloatMath.pi(30L));

I guess Float does not supports that much precision. 我猜Float不支持那么多的精度。 You may use BigDecimal for that. 您可以为此使用BigDecimal。

double doesn't have that much precision. 双精度没有那么高的精度。 Have a look at how the double type is implemented . 看一下double类型是如何实现的 For arbitrary precision have a look at BigDecimal 对于任意精度,请看BigDecimal

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM