gpt4 book ai didi

julia - 在 Julia : Equality of Float64 and BigFloat

转载 作者:行者123 更新时间:2023-12-02 06:48:12 25 4
gpt4 key购买 nike

在 Julia 1.0.0 REPL 中,我得到以下结果:

# Line 1: This make sense.  I did not expect a Float64 to equal a BigFloat.
julia> 26.1 == big"26.1"
false

# Line 2: This surprised me when Line 1 is considered. Again, like Line 1, I
# did not expect a Float64 to equal an equivalent BigFloat.
julia> 26.0 == big"26.0"
true

# Line 3: This I expected based on Line 1 behavior.
julia> 26.1 - 0.1 == big"26.1" - 0.1
false

# Line 4: This surprised me based on Line 1 behavior, but it might be
# explained based on Line 2 behavior. It seems to imply that if a Float64
# can be converted to an Integer it will compare equal to an equivalent BigFloat.
julia> 26.1 - 0.1 == big"26.1" - big"0.1"
true

似乎 Julia 在幕后做了一些事情来与 Float64 和 BigFloat 进行相等性比较,这使得第 2 行和第 4 行为真,而第 1 行和第 3 行为假。有什么建议吗?

关于“==”的 Julia 文档似乎没有涵盖此类内容: https://docs.julialang.org/en/v1/base/math/#Base.:==

编辑:根据下面@EPo 的有用评论,很容易使上面的所有比较都成为现实。例如,下面的第 1 行和第 3 行是正确的,尽管它们在上面是错误的:

# Line 1 is now true.
julia> 26.1 ≈ big"26.1"
true

# Line 3 is now true.
julia> 26.1 - 0.1 ≈ big"26.1" - 0.1
true

最佳答案

一些 float 可以精确表示(26.0)但不是全部,例如:

julia> using Printf
julia> @printf("%.80f",26.0)
26.00000000000000000000000000000000000000000000000000000000000000000000000000000000
julia> @printf("%.80f",0.1)
0.10000000000000000555111512312578270211815834045410156250000000000000000000000000

例如,小数 0.5、0.25、0.125 也可以用基于二进制的浮点表示法精确表示。所以例如你有:

julia> 26.125 - 0.125 == big"26.125" - 0.125
true

但0.1在二进制中是周期数,所以四舍五入。

julia> bitstring(0.1)
"0011111110111001100110011001100110011001100110011001100110011010"

最后 52 位表示二进制中的分数。 ( https://en.wikipedia.org/wiki/Double-precision_floating-point_format )

关于julia - 在 Julia : Equality of Float64 and BigFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52248341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com