## Math.random()

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
spynaz
Party member
Posts: 152
Joined: Thu Feb 28, 2013 5:49 am

### Math.random()

Is there are way to receive a random number WITH a decimal between 2 numbers? Example: math.random(1, 10) = 5.381298317

slime
Solid Snayke
Posts: 2887
Joined: Mon Aug 23, 2010 6:45 am
Contact:

### Re: Math.random()

This will give you a number between 1 and 10:

Code: Select all

1 + (math.random() * 9)

spynaz
Party member
Posts: 152
Joined: Thu Feb 28, 2013 5:49 am

### Re: Math.random()

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


slime
Solid Snayke
Posts: 2887
Joined: Mon Aug 23, 2010 6:45 am
Contact:

### Re: Math.random()

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.) spynaz
Party member
Posts: 152
Joined: Thu Feb 28, 2013 5:49 am

### Re: Math.random()

Ok.

slime
Solid Snayke
Posts: 2887
Joined: Mon Aug 23, 2010 6:45 am
Contact:

### Re: Math.random()

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

Code: Select all

function newRandom(min, max)
return min + math.random() * (max - min)
end

kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Contact:

### Re: Math.random()

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.

Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

### Re: Math.random()

That's what all their code samples use as well, though? Unless you think there's a problem?

Ragzouken
Citizen
Posts: 84
Joined: Fri Aug 10, 2012 7:59 am
Contact:

### Re: Math.random()

spynaz wanted real numbers in the range, those give you integers

T-Bone
Inner party member
Posts: 1492
Joined: Thu Jun 09, 2011 9:03 am

### Re: Math.random()

You could do

Code: Select all

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

### Who is online

Users browsing this forum: Google [Bot] and 7 guests