Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to set limits to math.random?

Asked by 5 years ago

I want to choose a random number between -5 and 5, but I don’t want -1 to 1 to be chosen. How do I set a limit, if that’s even possible?

0
I'm not sure if you can do that with math.random. All I know is that there's a minimum choice and a maximum choice. I don't think you can do it with Random.new() either. killerbrenden 1537 — 5y

3 answers

Log in to vote
0
Answered by
Avoxea 48
5 years ago
Edited 5 years ago

This is one way you could do it:

1local var1 = math.random(-5,-1)
2local var2 = math.random(1,5)
3local var3 = math.random(1,2)
4local finalVar = 0
5if var3 == 1 then
6    finalVar = var1
7elseif var3 == 2 then
8    finalVar = var2
9end

or you could do it this way:

01function chooseVar()
02    finalVar = math.random(-5,-1)
03    return finalVar
04end
05 
06repeat
07    if finalVar >= -1 and finalVar<= 1 then
08        chooseVar()
09    end
10until finalVar >= 1 or finalVar<= -1
11 
12print(finalVar) --just to make sure this worked correctly
0
kind of clunky but gets the job done Avoxea 48 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

you can set limits to math.random doing this

math.random(-5,5)

the first value is the minimum number and the second one is the maximum

0
btw i tested it using print densomenso999 11 — 5y
0
So how would I set a number between -5 to -1 and 1 to 5 into a variable. VexTrexYT 28 — 5y
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago
1local number = math.random(1,5)*((math.random(0,1)*2)-1)

This is probably the most simple way to do it, one line and no if statements

0
I couldn't tell if you wanted -1 and 1 to be part of it but I assumed so, if you don't want them then just change the 1,5 to a 2,5 PureLiteStudio 80 — 5y

Answer this question