-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug with range() and unsigned indices #44895
Comments
Can confirm on (somewhat recent) master. I think there are more places out there hiding like that, like #42528 previously.. Finding those will be a little bit of a challenge :/ |
I wonder how we could fix this. Casting it to an integer means that there would be indices that aren't representible. But ranges currently assume that you can have a negative index. I guess adding a special dispatch for unsigned integers that does some checking while leaving the normal integer one alone could work. |
Yeah, special casing Note that negative indices are still fine here, they can live happily in the The same fix should be applied to Lines 943 to 947 in 0d29712
as well. |
I was giving this a stab, the same functions in twiceprecision.jl also have to changed. function unsafe_getindex(r::StepRangeLen{T}, i::Unsigned) where T
i = Int(i)
u = i - r.offset
T(r.ref + u*r.step)
end It does mean that very large unsigned ints will fail. Another idea is to put the type cast behind an if statement. But that would be type unstable. |
My untested recommendation is (after bitter experience dealing with similar questions for computing length haha) is to force inbounds math via a branch here: function unsafe_getindex(r::StepRangeLen{T}, i::Integer) where T
i isa Bool && throw(ArgumentError("invalid index: $i of type Bool"))
if i < r.offset # 1 <= offset <= len && 1 <= i <= len
u = r.offset - i
return T(r.ref - u*r.step)
else
u = i - r.offset
return T(r.ref + u*r.step)
end
end and also needs to apply to
|
Would keeping the dispatch separated be better to avoid a branch on signed integers? Or would the performance difference not be that significant? |
There are a lot of cases where the same error happens. I will open a PR to get started. |
could this possibly be tagged for 1.10? it's pretty easy to encounter; many combinations of |
The snippet
gives
3.6893488147419105e18
instead of the expected-1.0
.The problem seems to be
julia/base/range.jl
Line 939 in 0d29712
UInt(1) - 6
underflows.The text was updated successfully, but these errors were encountered: