# Customised or exclusive random range

Hi folks
I have been trying to generate some random floats that avoid values > -0.1 and < 0.1, and as I’m not an experienced coder I came up with this hacky solution. In psuedo code I say "give me a random float between -2 and 2, but not if that number is between -0.1 and 0.1. So I used splat to give me an array of integers and then used minus to strip out the middle range.

``````mySamp = :glitch_robot1

excl = [*-5..5] - [*-1..1]

live_loop :test do
#stop
tick
myRate = (excl.shuffle.choose*(rand()+0.1))
slp = (1.0/myRate).abs
puts myRate
sample mySamp, rate: myRate
sleep slp
end
``````

PD-Pi

2 Likes

Here’s one way you could do it, by looping while generating random numbers, and if they are outside the excluded region you break out of the loop and return the value:

``````define :my_rand do
while 1
r = rand(-2..2)
if r < -0.1 or r > 0.1
return r
end
end
end

10.times do
puts my_rand
end
``````

As long as the excluded region is small compared to the full range, it should rarely loop more than once or twice, but there could be exceptional cases where it has to loop a lot of times before finding a good number, and slow the code down.

A better way might be like this:

``````define :my_rand do
r = rand(-2..1.8)
if r >= -0.1
r += 0.2
end
r
end

10.times do
puts my_rand
end
``````
1 Like