简体   繁体   English

双精度

[英]Double Precision

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? 但这对.NET不重要,为什么呢? 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. 但消息框显示:3.5请帮助我,谢谢。

The precision of a Double is 15 digits (17 digits internally). Double的精度为15位数字(内部为17位数字)。 The value that you calculate with Math.Pow is correct, but when you add it to value it just is too small to make a difference. 您使用Math.Pow计算的值是正确的,但是将其添加到value它太小而Math.Pow

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: 如果需要这种精度,则需要进行计算,然后将每个值转换为Decimal ,然后再将它们相加:

double value = 3.5;
double small = Math.Pow(10, -20);

Decimal result = (Decimal)value + (Decimal)small;

MessageBox.Show(result.ToString());

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" . 大卫·戈德伯格David Goldberg)的“每位计算机科学家应该知道的有关浮点算法的知识”都是一个很好的参考。

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. 但是,这些总是比浮点慢得多-在精度和速度之间进行权衡。

或者使用Decimal类型而不是double。

You can have precision, but it depends on what else you want to do. 您可以具有精度,但是这取决于您还想做什么。 If you put the following in a Console application: 如果将以下内容放入控制台应用程序:

double a = 1e-20;
Console.WriteLine(" a  = {0}", a);
Console.WriteLine("1+a = {0}", 1+a);

decimal b = 1e-20M;
Console.WriteLine(" b  = {0}", b);
Console.WriteLine("1+b = {0}", 1+b);

You will get 你会得到

 a  = 1E-20
1+a = 1
 b  = 0,00000000000000000001
1+b = 1,00000000000000000001

But Note that The Pow function, like almost everything in the Math class, only takes doubles: 但是请注意, Pow函数与Math类中的几乎所有东西一样,只需要加倍:

double Pow(double x, double y);

So you cannot take the Sine of a decimal (other then by converting it to double) 因此,您不能采用小数的正弦(否则请将其转换为双精度)

Also see this question . 也看到这个问题

Double precision means it can hold 15-16 digits. 双精度表示可以容纳15-16位数字。 3.5 + 1e-20 = 21 digits. 3.5 + 1e-20 = 21位数字。 It cannot be represented in double precicion. 它不能用双精度表示。 You can use another type like decimal. 您可以使用其他类型,例如十进制。

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

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