# 不要用浮点数 range，会变得不幸

``````julia> 1 - 1/7 + 4
4.857142857142858

julia> 1 + 4 - 1/7
4.857142857142857

julia> (1 - 1/7 + 4) == (1 + 4 - 1/7)
false

julia> (1 - 1/7 + 4) - (1 + 4 - 1/7)
8.881784197001252e-16

julia> eps(1 - 1/7 + 4)
8.881784197001252e-16
``````
``````julia> ( (1:5) .- 1/7 ) == ( collect(1:5) .- 1/7 )
false

julia> (1:5) .- 1/7
0.8571428571428572:1.0:4.857142857142858

julia> collect( (1:5) .- 1/7 )
5-element Vector{Float64}:
0.8571428571428572
1.8571428571428572
2.857142857142857
3.857142857142857
4.857142857142858

julia> collect(1:5) .- 1/7
5-element Vector{Float64}:
0.8571428571428572
1.8571428571428572
2.857142857142857
3.857142857142857
4.857142857142857
``````

``````julia> (1:5) .- 1/7
0.8571428571428572:1.0:4.857142857142858

julia> (1:5) .- 1/7 |> collect
5-element Vector{Float64}:
0.8571428571428572
1.8571428571428572
2.857142857142857
3.857142857142857
4.857142857142858

julia>

julia> (1 - 1/7):(5 - 1/7)
0.8571428571428572:1.0:3.857142857142857

julia> (1 - 1/7):(5 - 1/7) |> collect
4-element Vector{Float64}:
0.8571428571428572
1.8571428571428572
2.857142857142857
3.857142857142857
``````

``````julia> range(start=1-1/7, stop=5-1/7, length=5) |> collect
5-element Vector{Float64}:
0.8571428571428572
1.8571428571428572
2.8571428571428568
3.8571428571428568
4.857142857142857
``````

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use `numpy.linspace` for these cases.

1 个赞

``````julia> 1 + (-1/7 + 4) == 1 + (4 - 1/7)
true

julia> 1 + (4 - 1/7) == (1 + 4) - 1/7
false
``````
1 个赞

``````julia> 1 + NaN == NaN + 1
false

julia> 1 + NaN === NaN + 1
true
``````

When the arithmetic operations are correctly rounded, in any of the four rounding modes, floating-point addition and multiplication remain commutative.

—— [P27] 2.4 Lost or Preserved Properties of the Arithmetic on the Real Numbers

sf 还提到了次正规数（denormal number）的问题，这就扯到浮点数的标准及硬件实现了。

2 个赞