Skip to content
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

Incorrect conversion to unisigned integer #51063

Closed
LilithHafner opened this issue Aug 26, 2023 · 3 comments · Fixed by #51095
Closed

Incorrect conversion to unisigned integer #51063

LilithHafner opened this issue Aug 26, 2023 · 3 comments · Fixed by #51095
Labels
bug Indicates an unexpected problem or unintended behavior maths Mathematical functions

Comments

@LilithHafner
Copy link
Member

julia> convert(UInt32, 4.2949673f9)
0xffffffff

4.2949673f9 is one greater than the maximum value of a UInt32 (4.2949673f9 == typemax(UInt32)+1) so an inexact error should be thrown here:

function (::Type{$Ti})(x::$Tf)
    if ($(Tf(typemin(Ti))) <= x <= $(Tf(typemax(Ti)))) && isinteger(x)
        return unsafe_trunc($Ti,x)
    else
        throw(InexactError($(Expr(:quote,Ti.name.name)), $Ti, x))
    end
end

However, the comparison that happens is 4.2949673f9 <= Float32(typemax(UInt32)) which is true even though 4.2949673f9 > typemax(UInt32).

@LilithHafner LilithHafner added bug Indicates an unexpected problem or unintended behavior maths Mathematical functions labels Aug 26, 2023
@LilithHafner
Copy link
Member Author

unsafe_trunc calls llvm's fptoui under the hood so this result is a poison value

@gbaraldi
Copy link
Member

gbaraldi commented Aug 28, 2023

The issue is that at this value the eps of Float32 is 512 so

julia> Float32(typemax(UInt32))
4.2949673f9

julia> ans + 1 
4.2949673f9

and float32 can't represent typemax(UInt32) exactly (It's 4.294967295e9)

@LilithHafner
Copy link
Member Author

Here's a full list of failures:

julia> UInt128(3.402823669209385e38)
0x00000000000000000000000000000000

julia> UInt64(1.8446744073709552e19)
0xffffffffffffffff

julia> UInt64(1.8446744f19)
0xffffffffffffffff

julia> UInt32(4.2949673f9)
0xffffffff

julia> UInt128(1.8446744073709552e19)
0x00000000000000010000000000000000

for reference about what those float values are actually:

julia> UInt128.((1.8446744073709552e19, 1.8446744f19, 4.2949673f9))
(0x00000000000000010000000000000000, 0x00000000000000010000000000000000, 0x00000000000000000000000100000000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Indicates an unexpected problem or unintended behavior maths Mathematical functions
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants