Stephen Miller
Stephen Miller

Reputation: 33

Large Integer division error in Julia when using UInt128 data type

I get incorrect results when I divide large integers of type UInt128. The error seems to occur about the same spot, significant figure wise, that a float64 will round its result. Using something simple, like dividing by 2, I can easily verify that I am not getting the correct answer. Also I can use BigInt types to verify that I am indeed seeing what seem to be significant figure errors while using UInt128 variable.

I am still fairly new to Julia and not familiar enough with the inner workings of the language to know why this is happening and when to expect these kinds of results. Can someone please give me some insight as to why/how this is occurring.

For example:

xb::BigInt = big"40282366920938463463374607431768211456"
ub::BigInt = big"2"

xu::UInt128 = parse(UInt128,"40282366920938463463374607431768211456")
uu::UInt128 = parse(UInt128, "2")

println("Initial value for xb = " , xb)    
println("Initial value for xu = " , xu)   

gb::BigInt = xb / ub
gu::UInt128 = xu / uu
g1::UInt128 = UInt128(40282366920938463463374607431768211456) / UInt128(2)
g2 = UInt128(40282366920938463463374607431768211456) / UInt128(2)
println("Division result using BigInt            = ", gb)
println("Division result using UInt128 variables = ", gu)
println("Division result using UInt128 typecasts = ", g1)
println("Division result using UInt128 julia decides = ", g2)
println(typeof(g2)) 

Output:

julia> include("uint128_test.jl")
Initial value for xb = 40282366920938463463374607431768211456
Initial value for xu = 40282366920938463463374607431768211456
Division result using BigInt            = 20141183460469231731687303715884105728
Division result using UInt128 variables = 20141183460469232747289327097010454528
Division result using UInt128 typecasts = 20141183460469232747289327097010454528
Division result using UInt128 julia decides = 2.0141183460469233e37
Float64

Upvotes: 3

Views: 215

Answers (1)

Oscar Smith
Oscar Smith

Reputation: 6378

Integer division in Julia promotes to Float64. you want to use div or ÷ for integer division.

For a very brief version of this, 3/2 = 1.5

Upvotes: 4

Related Questions