bashrandomfloating-pointcommand-line-tool

How do I generate a file of random (IEEE-754 single-precision) floats?


In a bash script, I want to generate a file containing IEEE-754 single-precision floating point values (i.e not a text file). I want them to have a uniform distribution over some range (which I have as string variables, $min_val and $max_val ; e.g. -100.0 and 200.0 respectively). I don't care that much about the "quality" of randomness, so anything passable to the naked human eye will do; and I don't want NaNs or infinities.

What's a convenient way to do that? I can't just user random characters from /dev/urandom and such.

Notes:


Solution

  • My Perl seems to pack floats into the IEEE-754 format.

    You may need to change this for endian-ness:

    perl -e '
        ($min,$max,$count) = @ARGV;
        print pack "f*", $min + rand($max-$min) for 1..$count;
    ' $min $max $count > floatfile
    

    For reference:

    perl -e 'print pack "f*", Inf, Nan, -118.625, 0.15625' | od -x
    

    gives, on my machine:

    0000000 0000 7f80 0000 ffc0 4000 c2ed 0000 3e20
    0000020
    

    "f<*" forces little-endian; "f>*" forces big-endian.