问题描述
当双倍值变得非常大时,为什么会出现精度损失?
Why exactly does a loss of precision occur when the values become very large in double?
示例代码:
double e1 = 1e20 + 8192;
double e11 = 1e20 + 8193;
double e2 = 1e20;
Console.WriteLine("E-notation");
Console.WriteLine(e1 == e2);
Console.WriteLine(e11 == e2);
输出:
The output:
正常表示法
正确
错误
Normal notation
True
False
为什么符号是否起作用,无论我将其写为正常数字还是电子符号:
And why does the notation play a role, whether i write it as normal number or in E-notation:
double d1 = 10000000000000000000 + 1024;
double d11 = 10000000000000000000 + 1025;
double d2 = 10000000000000000000;
Console.WriteLine("Normal notation");
Console.WriteLine(d1 == d2);
Console.WriteLine(d11 == d2);
E-notation
True
False
E-notation
True
False
推荐答案
此外,尽可能小的代表值( epsilon )是标准的结果。双范围中的值多于它可以准确显示的值,因此您会出现舍入错误。
如果你将非常大和非常小的值组合在一起,你往往会看到这些问题。但你也可以用简单的数字看到它们。双精度对于浮点计算很有用,但不是很大或非常小。
Additionally the smallest possible representative value (epsilon) is a consequence of the standard. There are more values in the double range than it can accurately show so you get rounding errors. If you're combining very large and very small values together you tend to see these problems. But you can also see them with even simple numbers. Doubles are useful for floating point calculations but not very large or very small.
在C#中,你应该使用十进制来进行大型计算,例如财务计算。它具有更高的精度,旨在解决这些问题。
In C# you should use decimal for large calculations such as financial. It has a larger precision and is designed to solve these problem.
这篇关于数据类型中的大值精度损失加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!