Julia: Overflow in mod1

Created on 20 Dec 2016  路  4Comments  路  Source: JuliaLang/julia

julia> mod1(1, typemax(Int))
1

julia> mod1(0, typemax(Int))
9223372036854775807

julia> mod1(1, typemax(Int))
1

julia> mod1(2, typemax(Int))
9223372036854775807

julia> mod1(3, typemax(Int))
1

julia> mod1(4, typemax(Int))
2

julia> mod1(5, typemax(Int))
3

julia> mod1(6, typemax(Int))
4

It's fine if this is meant to overflow as is, but I thought I'd bring it up at least in case it's unintended.
This is julia 0.5, OSX.

bug maths

All 4 comments

The general approach of Julia is that overflow might be acceptable for very cheap operations (e.g. +, *), but operations that are expensive anyway (such as mod1) need to return the correct result, if that result is representable, or need to throw an exception otherwise. A good example here is div(typemin(Int), -1); the result would be typemax(Int)+1, which is not representable, and thus div throws an exception in this case.

Congratulations, you found a bug.

Note that mod1(Int8(2), typemax(Int8)) returns 127 (also wrong), and thus a straightforward loop checking all possible Int8 pairs for mod1 would make an interesting test case.

fld1 has the same behavior.

I think it's because both function definitions for integer types use the operation x+y-T(1) which can overflow.

I tried coming up with a solution based on checking if it would overflow (negative or positive values) and returning a special case for those occasions, it returned good values but slowed things down too much (it was slower than the definition for Real).

For anyone that works on this, I think there is another bug with the integer version of mod1. My understanding is that the result should never be 0, but if the first argument is 0 and the second argument is negative, then the function returns 0.

For example

julia> mod1(0, -5)
0

julia> mod1(0., -5.)
-5.0

I can not reproduce it. I have compiled the latest julia.
Don't know if its fixed since, there is no reference to other issue or PR
@quinnj is it fixed?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sbromberger picture sbromberger  路  3Comments

iamed2 picture iamed2  路  3Comments

i-apellaniz picture i-apellaniz  路  3Comments

wilburtownsend picture wilburtownsend  路  3Comments

helgee picture helgee  路  3Comments