在Java中我应该使用多少有效数字用于双重文字?

时间:2022-11-28 06:55:30

How many significant digits should I use when defining a double literal in Java? This is assuming that I am trying to represent a number with more significant figures than a double can hold.

在Java中定义双字面时,我应该使用多少有效数字?这假设我试图表示一个数字比一个双重数字更重要的数字。

In Math.java I see 20 and 21:

在Math.java中,我看到20和21:

public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;

This is more than the 15-17 significant digits provided by IEEE 754. So what's the general rule-of-thumb?

这超过了IEEE 754提供的15-17位有效数字。那么一般的经验法则是什么?

2 个解决方案

#1


4  

A double has 15-17 decimal digits precision.

双精度为15-17十进制数。

I can't answer why those constants appear with 20 decimals, but you'll find that those digits are dropped:

我无法回答为什么这些常量出现20位小数,但你会发现这些数字被删除:

2.7182818284590452354d == 2.718281828459045d

2.7182818284590452354d == 2.718281828459045d

#2


1  

If you read the javadocs for Math.E and Math.PI you'll see this (emphasis mine):

如果你阅读了Math.E和Math.PI的javadocs,你会看到这个(强调我的):

The double value that is closer than any other [...]

双重值比任何其他[...]更接近

If your literals can be exactly represented as a double, then do that. Otherwise, find the closest value that is representable.

如果您的文字可以精确地表示为double,那么就这样做。否则,找到可表示的最接近的值。

Of course, depending on how your values are used, it may not matter if you are 'only' accurate to, say, 10 significant figures.

当然,根据你的价值观的使用方式,如果你对10个有效数字“仅”准确,则可能无关紧要。

#1


4  

A double has 15-17 decimal digits precision.

双精度为15-17十进制数。

I can't answer why those constants appear with 20 decimals, but you'll find that those digits are dropped:

我无法回答为什么这些常量出现20位小数,但你会发现这些数字被删除:

2.7182818284590452354d == 2.718281828459045d

2.7182818284590452354d == 2.718281828459045d

#2


1  

If you read the javadocs for Math.E and Math.PI you'll see this (emphasis mine):

如果你阅读了Math.E和Math.PI的javadocs,你会看到这个(强调我的):

The double value that is closer than any other [...]

双重值比任何其他[...]更接近

If your literals can be exactly represented as a double, then do that. Otherwise, find the closest value that is representable.

如果您的文字可以精确地表示为double,那么就这样做。否则,找到可表示的最接近的值。

Of course, depending on how your values are used, it may not matter if you are 'only' accurate to, say, 10 significant figures.

当然,根据你的价值观的使用方式,如果你对10个有效数字“仅”准确,则可能无关紧要。