[英]C# double precision problem
Imagine that a - b < c (a, b, c are C# doubles). 想象一下a - b <c (a,b,c是C#的双打)。 Is it guaranteed that a < b + c ?
是否保证<b + c ?
Thanks! 谢谢!
EDIT 编辑
Let's say that the arithmetical overflow doesn't occur unlike the following example: 假设与以下示例不同,不会出现算术溢出:
double a = 1L << 53;
double b = 1;
double c = a;
Console.WriteLine(a - b < c); // Prints True
Console.WriteLine(a < b + c); // Prints False
Imagine that Math.Abs(a) < 1.0 && Math.Abs(b) < 1.0 && Math.Abs(c) < 1.0 想象一下, Math.Abs(a)<1.0 && Math.Abs(b)<1.0 && Math.Abs(c)<1.0
No. Suppose a = c, a very large number, and b is a very small number. 不。假设a = c,非常大的数字,b是非常小的数字。 It's possible that
a - b
has a representation less than a
, but a + b
is so close to a
(and bigger) that it still ends up being most precisely representable as a
. 有可能
a - b
的表示小于a
,但a + b
非常接近a
(并且更大),它仍然最终可以最精确地表示为a
。
Here's an example: 这是一个例子:
double a = 1L << 53;
double b = 1;
double c = a;
Console.WriteLine(a - b < c); // Prints True
Console.WriteLine(a < b + c); // Prints False
EDIT: 编辑:
Here's another example, which matches your edited question: 这是另一个与您编辑过的问题相符的示例:
double a = 1.0;
double b = 1.0 / (1L << 53);
double c = a;
Console.WriteLine(a - b < c); // Prints True
Console.WriteLine(a < b + c); // Prints False
In other words, when we subtract a very small number from 1, we get a result less than 1. When we add the same number to 1, we just get 1 back due to the limitations of double precision. 换句话说,当我们从1中减去一个非常小的数字时,我们得到的结果小于1.当我们将相同的数字加到1时,由于双精度的限制,我们只得到1。
no not always: 不总是:
double a = double.MaxValue;
double b = double.MaxValue;
double c = 0.1;
Console.WriteLine(a - b < c); // True
Console.WriteLine(a < b + c); // False
This link speaks about floating-point arithmetic properties, and could be very interesting: 这个链接讲的是浮点算术属性,可能非常有趣:
In particular, search for Properties of Relations 特别是,搜索关系属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.