Search code examples
randomfish

Generating random floats in fish shell


I have been using fish's random start stop to generate a random integer, but I was curious if there was a way to get a random float from within fish or whether I need to use another program.

My current method feels a bit hack-y to me. For example, here's how I'd generate something like a float, but obviously to only one decimal place. Is there a better way to do this?

set myNum (random 0 9).(random 0 9)

Solution

  • Many languages go the opposite route of Fish shell's script, where the result of the random function is 0 <= r < 1. In that case, to obtain an integer, you just multiply by the max number you want.

    So for Fish, I'd sort-of do the reverse process -- Divide to obtain the precision you want.

    For your particular example:

    set myNum (math (random 0 99)/10)
    

    Of course, if you want to go from 0.0 to 10.0 inclusive (which wouldn't be possible with your example):

    set myNum (math (random 0 100)/10)
    

    If you to replicate the 0 <= r < 1 style to 4 decimal places:

    set myNum (math (random 0 9999)/10000)
    

    This will work to a maximum of 6 decimal places.