How to best create a random float in a range between two floats

Viewed 37644

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
4 Answers

In 1.9 and 2.0 you can give a range argument to rand:

irb(main):001:0> 10.times { puts rand Math::E..Math::PI }
3.0656267148715446
2.7813979580609587
2.7661725184200563
2.9745784681934655
2.852157154320737
2.741063222095785
2.992638029938756
3.0713152547478866
2.879739743508003
2.7836491029737407
=> 10
Related