朱莉娅(Julia

发布于 2025-02-13 22:21:09 字数 549 浏览 1 评论 0原文

我正在学习 Julia 当前,并且遇到了一个奇怪的结果(我认为这不是朱莉娅的特定行为! ),我渴望找出原因。在朱莉娅(Julia)中,可以使用==isequal()检查两个值(例如整数,float等)之间的平等。例如,您可以检查4和Expression 2+2之间的平等:

julia> isequal(4, 2+2)
true

但是,当我尝试以下两个语句时,我得到了意外的结果:

julia> isequal(0.6, 0.5 + 0.1)
true

julia> isequal(0.6, 0.4 + 0.2)
false

我我感到困惑为什么会有所不同。任何帮助将不胜感激。

朱莉娅(Julia)的功能还可以执行不精确的平等比较吗?

I'm learning Julia currently and have encountered a strange result (which I don't think to be Julia's specific behavior!), and I'm eager to find out why. In Julia, one can check the equality between two values (like Integer, Float, etc.) using == or isequal(). For example, you can check the equality between 4 and the expression 2+2 like this:

julia> isequal(4, 2+2)
true

But when I tried these two following statements, I got an unexpected result:

julia> isequal(0.6, 0.5 + 0.1)
true

julia> isequal(0.6, 0.4 + 0.2)
false

I'm confused why this differs. Any help would be appreciated.

Also is there function in Julia that can perform an inexact equality comparison?

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

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

发布评论

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

评论(1

优雅的叶子 2025-02-20 22:21:09

0.10.2之类的数字不是二进制系统中的合理数字,因此您最终会出现舍入错误。此行为是根据 ieee floating Point Standard Standard 例如。

在朱莉娅(Julia)中,有isapprox具有相应运算符的功能。


julia> 0.2 + 0.4 == 0.1 + 0.5
false

julia> 0.2 + 0.4 ≈ 0.1 + 0.5
true

另一个选项是将您的算术带到有理数:


julia> 2//10 + 4//10 == 1//10 + 1//2
true

请注意,在浮点和有理数之间转换并不容易:

julia> Rational(0.2)
3602879701896397//18014398509481984

而是使用具有可选公差参数的合理函数:

julia> rationalize(0.2)
1//5

The numbers such as 0.1 or 0.2 are not rational numbers in the binary system so you end up having rounding errors. This behaviour is according to the IEEE floating point standard, and is present in all mainstream programming languages (eg. the same behavior can be observed in Python, C++, C#, Java or even Microsoft Excel).

In Julia there is the isapprox function having a corresponding operator .


julia> 0.2 + 0.4 == 0.1 + 0.5
false

julia> 0.2 + 0.4 ≈ 0.1 + 0.5
true

Another option would be to bring your arithmetic to rational numbers:


julia> 2//10 + 4//10 == 1//10 + 1//2
true

Note that converting between floats and rational numbers is not so easy:

julia> Rational(0.2)
3602879701896397//18014398509481984

Instead use rationalize function that has optional tolerance parameter:

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