I know that I can generate random floats with rand(max). I tried to generate a float in a range, this shouldn't be hard. But e.g rand(1.4512) returns 0, thus rand isn't calculating with floats. Now I tried a little trick, converting the thing to an integer and after randomizing a fitting number in my desired range, calculating it back to a float.. which is not working.
My question is how to do this in a better way. If there is no better way, why is this one not working? (Maybe it's too late for me, I should've started sleeping 2 hours ago..). The whole thing aims to be a method for calculating a "position" field for database records so users can order them manually. I've never done something like this before, maybe someone can hint me with a better solution.
Here's the code so far:
def calculate_position(@elements, index)
min = @elements[index].position
if @elements[index + 1].nil?
pos = min + 1
else
pos = min + (rand(@elements[index + 1].position * 10000000000) / 10000000000)
end
return pos
end
Thanks!
question from:
https://stackoverflow.com/questions/1711681/how-to-best-create-a-random-float-in-a-range-between-two-floats 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…