How to generate random float in lua?

13,218

Solution 1

This should generate random floats between 1 (inclusive) and 100 (exclusive)

math.random() + math.random(1, 99)

Solution 2

You can also use something like this to get a number between lower and greater

function randomFloat(lower, greater)
    return lower + math.random()  * (greater - lower);
end

Solution 3

Just posting for fun, but you can use math.random() with no arguments to do this :P

print(math.floor((math.random()*100)+0.5))
Share:
13,218
Author by

user0103

Updated on June 04, 2022

Comments

  • user0103 7 months

    I need to generate random float in Lua. It needs to be > 1, so math.random() is not a solution.

    How can I do this?

  • Stomp
    Stomp about 10 years
    math.random(1, 100) will do the same
  • Stals over 9 years
    It still could be helpfull for people that find this question
  • Phrogz
    Phrogz about 8 years
    @Stomp math.random(1,100) generates random integers within that range, not floats.
  • klewis
    klewis over 1 year
    This helped me out tremendously. Thanks for posting!