Search code examples
perlieee-754

What is the perl equivalent to Java's Double.doubleToLongBits()?


I have two floating point numbers and I want to compute their difference in Units in Last Place (ULP). In Java this is:

Double.doubleToLongBits(a) - Double.doubleToLongBits(b)

What is the equivalent in Perl?


Solution

  • On a Perl with double-precision floats[1] and unsigned integers at least 64 bits in size[2], you can use the following:

    unpack('Q', pack('d', $n))
    

    For example,

    $ perl -e'
       use Config qw( %Config );
    
       die("Not supported\n")
          if $Config{nvsize} != 8
          || $Config{uvsize} < 8;
    
       printf("%X\n", unpack("Q", pack("d", -0.1)));
    '
    BFB999999999999A
    

    1. perl -V:nvsize gives 8
    2. perl -V:uvsize gives 8 or higher