JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.65k stars 5.48k forks source link

`Int32` converted to `Float64` when using `float(Int32)` #55975

Closed albertomercurio closed 3 weeks ago

albertomercurio commented 3 weeks ago

Hello,

as the title, it was surprising that float(Int32(1)) gives a Float64. Is there a reason behind this choice? Or is it just a bug?

I would have expected it to have maintained the same precision.

giordano commented 3 weeks ago

The float docstring makes no promise of keeping the same data size and the example shows an Int32 being converted to Float64, so this all seems to be on purpose.

chelate commented 3 weeks ago

Float32(2^32-1)-Float64(2^32-1) = 1.0, because of the exponent you need more float bits to represent integers to the same precision. Float32 only has 24 bits of fractional precision.

albertomercurio commented 3 weeks ago

Ok, but the same would hold for Int64, where the corresponding float would be a possible Float128 and so on. While here it seems that there is an exception.

I have to define a function with very basic operations like +, *, /, exp, and I want to keep the same precision. But if I use Int32 as arguments, then I get Float64.

timholy commented 3 weeks ago

Julia doesn't have Float128 in Base (you need Quadmath.jl for that), and hardware support is not widespread.

Presumably the policy is: if we can represent it exactly using a type with hardware support, do so. So this is not an exceptional case. Moreover, this was all hashed out long ago and any changes now would be incredibly disruptive.

giordano commented 3 weeks ago

I'm not sure what you mean by "same precision" as there's little correlation between the the integer datatype and the floating point datatype (the range of numbers they can represent is different and the distance between consecutive numbers is in general different), apart from having the same size for their canonical representations. Besides, the change you suggest would be breaking.

If you really want to do that and don't want to wait for a hypothetical Julia v2.0 (and no assurance this idea will be accepted anyway), surely you can define a custom function which achieves what you want.