Math.random()

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
User avatar
spynaz
Party member
Posts: 152
Joined: Thu Feb 28, 2013 5:49 am

Math.random()

Post by spynaz »

Is there are way to receive a random number WITH a decimal between 2 numbers? Example: math.random(1, 10) = 5.381298317
User avatar
slime
Solid Snayke
Posts: 3133
Joined: Mon Aug 23, 2010 6:45 am
Location: Nova Scotia, Canada
Contact:

Re: Math.random()

Post by slime »

This will give you a number between 1 and 10:

Code: Select all

1 + (math.random() * 9)
User avatar
spynaz
Party member
Posts: 152
Joined: Thu Feb 28, 2013 5:49 am

Re: Math.random()

Post by spynaz »

slime wrote:This will give you a number between 1 and 10:

Code: Select all

1 + (math.random() * 9)
Can't you just do this?

Code: Select all

math.random()*10
User avatar
slime
Solid Snayke
Posts: 3133
Joined: Mon Aug 23, 2010 6:45 am
Location: Nova Scotia, Canada
Contact:

Re: Math.random()

Post by slime »

You can, but it'll give you a number in the range of [0, 10] instead of [1, 10] (the latter being what your example asked for.) :P
User avatar
spynaz
Party member
Posts: 152
Joined: Thu Feb 28, 2013 5:49 am

Re: Math.random()

Post by spynaz »

Ok.
User avatar
slime
Solid Snayke
Posts: 3133
Joined: Mon Aug 23, 2010 6:45 am
Location: Nova Scotia, Canada
Contact:

Re: Math.random()

Post by slime »

You could make a function out of it, as well:

Code: Select all

function newRandom(min, max)
    return min + math.random() * (max - min)
end
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Math.random()

Post by kikito »

Hmm... guys, according to the lua-users wiki,
  • math.random() with no arguments generates a real number between 0 and 1.
  • math.random(upper) generates integer numbers between 1 and upper.
  • math.random(lower, upper) generates integer numbers between lower and upper.
I just tried it and it seems to work that way.
When I write def I mean function.
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: Math.random()

Post by Plu »

That's what all their code samples use as well, though? Unless you think there's a problem?
User avatar
Ragzouken
Citizen
Posts: 84
Joined: Fri Aug 10, 2012 7:59 am
Contact:

Re: Math.random()

Post by Ragzouken »

spynaz wanted real numbers in the range, those give you integers
User avatar
T-Bone
Inner party member
Posts: 1492
Joined: Thu Jun 09, 2011 9:03 am

Re: Math.random()

Post by T-Bone »

You could do

Code: Select all

math.random(max-1) + math.random()
too, but there's rarely a point in that.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 198 guests