Reputation: 1575
I am trying to view the bitstring of the largest positive integer that can be exactly represented using Julia. Wikipedia says that 2^1024 * (1-2^(-53)) is the integer. However, when I try using Julia, the bitstring is all zeros.
julia> bitstring(Float64( 2^1024 - 2^971 ))
"0000000000000000000000000000000000000000000000000000000000000000"
The bitstring I am expecting is
0 11111111110 1111111111111111111111111111111111111111111111111111
Can you please help me clarify why this discrepancy happens?
Upvotes: 3
Views: 579
Reputation: 12654
2^1024 - 2^971
overflows before you convert to Float64
. Instead you can do
julia> bitstring(prevfloat(typemax(Float64)))
"0111111111101111111111111111111111111111111111111111111111111111"
There are a few advantages over the big
approach: You don't have to know what the max representable value is -- 2^1024 - 2^971; it works for many different types (you could do the same with Float32
, etc); and it's faster.
For integer type T
you would do
bitstring(typemax(T))
The reason for using prevfloat
with floats, is that typemax(Float64)
is Inf
;
Upvotes: 9
Reputation: 20950
Those powers of integers overflow to zero integers before becoming floats. You can work in BigInt
, though:
julia> 2^1024 - 2^971
0
julia> big"2"^1024 - big"2"^971
179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368
julia> Float64(big"2"^1024 - big"2"^971)
1.7976931348623157e308
julia> bitstring(ans)
"0111111111101111111111111111111111111111111111111111111111111111"
Or alternatively convert the input integers to floats already.
Upvotes: 6