C#双精度问题

发布于 2024-09-18 01:11:42 字数 496 浏览 4 评论 0原文

想象一下 a - b c(a、b、c 是 C# 双精度数)。是否保证a < b + c?

谢谢!

编辑
假设不会发生算术溢出,与以下示例不同:

double a = 1L << 53;
double b = 1;
double c = a;

Console.WriteLine(a - b < c); // Prints True
Console.WriteLine(a < b + c); // Prints False

想象一下 Math.Abs​​(a) Math.Abs​​(a) 1.0&& Math.Abs​​(b) < 1.0&& Math.Abs​​(c) < 1.0

Imagine that a - b < c (a, b, c are C# doubles). Is it guaranteed that a < 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迟月 2024-09-25 01:11:42

不。假设a = c,一个非常大的数,而b 是一个非常小的数。 a - b 的表示形式可能小于 a,但 a + ba 非常接近(甚至更大)它最终仍然可以最精确地表示为 a

这是一个例子:

double a = 1L << 53;
double b = 1;
double c = a;

Console.WriteLine(a - b < c); // Prints True
Console.WriteLine(a < b + c); // Prints False

编辑:

这是另一个例子,与您编辑的问题相匹配:

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

换句话说,当我们从 1 中减去一个非常小的数字时,我们得到的结果小于 1。当我们将相同的数字加到 1 时,我们就得到1.由于双精度的限制返回。

No. Suppose a = c, a very large number, and b is a very small number. 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.

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.

︶葆Ⅱㄣ 2024-09-25 01:11:42

不,并不总是:

        double a = double.MaxValue;
        double b = double.MaxValue;
        double c = 0.1;
        Console.WriteLine(a - b < c); // True
        Console.WriteLine(a < b + c); // False

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
枉心 2024-09-25 01:11:42

此链接讨论浮点算术属性,可能非常有趣:

浮点谬误

特别是,搜索关系属性

This link speaks about floating-point arithmetic properties, and could be very interesting:

FLOATING-POINT FALLACIES

In particular, search for Properties of Relations

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文