-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Description
We have observed unexpected results for some ranges with floating point numbers. Here is a short example:
Let's construct a vector with x-coordinates (xv) and with values in-between (xc).
$>julia
julia> xmin = 0.0;
julia> xmax = 1.86038;
julia> Lx = xmax - xmin;
julia> nx = 7;
julia> dx = Lx/nx;
julia> xv = [xmin:dx:xmax...]
8-element Array{Float64,1}:
0.0
0.2657685714285714
0.5315371428571428
0.7973057142857143
1.0630742857142856
1.3288428571428572
1.5946114285714286
1.86038
julia> xc = [xmin+dx/2:dx:xmax-dx/2...]
6-element Array{Float64,1}:
0.1328842857142857
0.39865285714285714
0.6644214285714285
0.93019
1.1959585714285714
1.4617271428571428
We can observe that xc contains 6 elements rather than 7 elements as expected. Concretely, we would expect xc to contain a 7th value being approximately xmax-dx/2
julia> xmax-dx/2
1.7274957142857141
in particularly given that we have:
julia> xmax-dx/2 - xc[end] ≈ dx
true
I suppose that xc contains no 7th value, because xmin+dx/2 + (nx-1)*dx
julia> xmin+dx/2 + (nx-1)*dx
1.7274957142857144
is greater than the end value of the range (xmax-dx/2):
julia> xmin+dx/2 + (nx-1)*dx > xmax-dx/2
Finally, compare with the result obtained with linspace where the analogically computed xc contains 7 values:
julia> xc = LinRange(xmin+dx/2, xmax-dx/2, nx)
7-element LinRange{Float64}:
0.132884,0.398653,0.664421,0.93019,1.19596,1.46173,1.7275
I have seen that the algorithm used to compute ranges with floating points has been discussed a lot in 2013. However, I believe the algorithm needs to be revisited one more time following the above example.
Thanks!