Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Largest positive integer which can be represented in Julia using Float64

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?

like image 929
honeybadger Avatar asked Jul 25 '26 22:07

honeybadger


1 Answers

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;

like image 77
DNF Avatar answered Jul 28 '26 15:07

DNF