双精度
我有一个代码,但我不明白它。 我正在开发一个应用程序,精度非常重要。 但这对于.NET来说并不重要,为什么呢? 我不知道。
double value = 3.5;
MessageBox.Show((value + 1 * Math.Pow(10, -20)).ToString());
但消息框显示:3.5 请帮助我,谢谢。
I have a code, and I do not understand it. I am developing an application which precision is very important. but it does not important for .NET, why? I don't know.
double value = 3.5;
MessageBox.Show((value + 1 * Math.Pow(10, -20)).ToString());
but the message box shows: 3.5
Please help me, Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您正在做任何精度非常重要的事情,您需要了解浮点的局限性。 一个很好的参考是 David Goldberg 的“每个计算机科学家应该了解浮点运算” ”。
您可能会发现浮点无法提供足够的精度,您需要使用十进制类型。 然而,它们总是比浮点慢得多——这是精度和速度之间的权衡。
If you're doing anything where precision is very important, you need to be aware of the limitations of floating point. A good reference is David Goldberg's "What Every Computer Scientist Should Know About Floating-Point Arithmetic".
You may find that floating-point doesn't give you enough precision and you need to work with a decimal type. These, however, are always much slower than floating point -- it's a tradeoff between accuracy and speed.
你可以做到精确,但这取决于你还想做什么。 如果您将以下内容放入控制台应用程序中:
您将得到
但请注意,
Pow
函数与 Math 类中的几乎所有内容一样,仅采用双精度数:因此您不能采用小数的正弦值(其他然后将其转换为双精度)
另请参阅此问题。
You can have precision, but it depends on what else you want to do. If you put the following in a Console application:
You will get
But Note that The
Pow
function, like almost everything in the Math class, only takes doubles:So you cannot take the Sine of a decimal (other then by converting it to double)
Also see this question.
或者使用 Decimal 类型而不是双倍的。
Or use the Decimal type rather than double.
Double
的精度为 15 位(内部为 17 位)。 使用Math.Pow
计算的值是正确的,但是当您将其添加到value
时,它太小了,无法产生影响。编辑:
Decimal 可以处理该精度,但不能处理计算。 如果您想要该精度,则需要进行计算,然后将每个值转换为
Decimal
,然后再将它们相加:The precision of a
Double
is 15 digits (17 digits internally). The value that you calculate withMath.Pow
is correct, but when you add it tovalue
it just is too small to make a difference.Edit:
A Decimal can handle that precision, but not the calculation. If you want that precision, you need to do the calculation, then convert each value to a
Decimal
before adding them together:双精度意味着它可以容纳 15-16 位数字。 3.5 + 1e-20 = 21 位数字。 它不能用双精度表示。 您可以使用其他类型,例如十进制。
Double precision means it can hold 15-16 digits. 3.5 + 1e-20 = 21 digits. It cannot be represented in double precicion. You can use another type like decimal.