Hi!
I came accross a float-precision issue that I want to share and ask if there is a solution for my problem.
I define an array of coordinates, an equally-sized array for the result, and I want to fill the second array with numbers in segmentwise fashion through conditional indexing. This works fine for integer coordinates, but gets totally confusing (for me) with float coordinates.
I realize, isapprox points into the right direction, but its not fixing the issue entirely.
Here’s my code
#integer version
x = 0:1:20
seg_size = 2
seg_period = 4
I = zeros(Int64,size(x))
I[((x .% seg_period).>=0) .& ((x .% seg_period).<seg_size)] .= 2
I[((x .% seg_period).>=seg_size) .& ((x .% seg_period).<seg_period)] .= 1
println(I)
#float version
x = 0:.025:.5
seg_size = .05
seg_period = .1
I = zeros(Int64,size(x))
I[((x .% seg_period).>=0) .& ((x .% seg_period).<seg_size)] .= 2
I[((x .% seg_period).>=seg_size) .& ((x .% seg_period).<seg_period)] .= 1
println(I)
#float with isapprox
I = zeros(Int64,size(x))
I[(((x .% seg_period).>0) .| ((x .% seg_period).≈0)) .& ((x .% seg_period).<seg_size)] .= 2
I[(((x .% seg_period).>seg_size) .| ((x .% seg_period).≈seg_size)) .& ((x .% seg_period).<seg_period)] .= 1
println(I)
output:
[2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2]
[2, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 1, 2, 2, 1, 2, 2, 2, 1, 1]
[2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1]
The integer version (first output line) is nicely alternating between 1 and 2, which is the expected result.
The float version (second output line) has several mis-assignments due to float precision.
The float version using isapprox (third output line) can solve some issues, where the >= condition failed due to float precision, but cannot solve the issue where the < condition becomes true although the arguments are approximately equal.
So my question:
- Is there any better way to do things like that while keeping the code quite readable?
- Is there or should there be a approximate-version of >, <, >=, <= so that such an example (with appearantly very simple numbers) would work as naively expected?
Looking forward to your suggestions.