Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pass a range of floats to rand

If you want to "create a random float in a range between two floats", just pass a range of floats to rand.

rand(11.2...76.9)

(Tested with Ruby 2.1)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...