As part of some Ruby-Processing work I’m doing, I needed a random number within a specified range. Processing has its own random function, but I wanted to use Ruby.
I needed a random number in the interval (-range, range). I immediately thought, “specify the max value range*2 as a param to rand, and then subtract range to get it into the interval -range to range.” My autopilot first attempt yielded:
num = rand(range*2.0) - range
However, I didn’t read the documentation for Kernel#rand closely. According to the docs, the max parameter is converted to an integer:
max1 = max.to_i.abs
This means that when I use a float less than zero as the range, say 0.25, it’s converted to 0. When zero is passed in, the range for rand is from 0 to 1.
All this makes sense, but I just didn’t think about it at first. Instead of passing in a max parameter, I needed to manipulate rand’s output to get what I wanted:
num = rand*range*2.0 - range
That’s better.
In general, for a random number in the interval (min, max), you would use:
num = rand*(max - min) - min
This post is tagged
