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

How can I randomize math.random even more?

Asked by 7 years ago

ok so I know how to do this

math.random()*0.5

but what if I would want to choose a random number between -0.5 and 0.5 instead of 0 and 0.5?

4 answers

Log in to vote
0
Answered by
Link150 1355 Badge of Merit Moderation Voter
7 years ago
Edited 7 years ago

You don't want to randomize it more, you simply want to move the range of randomly generated values on the number line.

math.random() (with no arguments) will give you a floating point number in the range [0.0, 1.0[. Note how the last square brackets is open. This means math.random() will never return exactly 1.0; it is outside the range. It will return 0.9999999... at most.

If you want to change that range from [0.0, 1.0[ to [-0.5, 0.5[ then it's as simple as offsetting the return value by -0.5:

local n = math.random() - 0.5

Think of a number line, and visually highlight the range [0.0, 1.0[ on that number line. Now, imagine yourself moving that range until its limits are [-0.5, 0.5[. As you should already know from primary school, moving on the number line is done through addition and subtraction. To move right you do an addition; to move left you do a subtraction.

Multiplying the return value of math.random instead scales or resizes the range of possible randomly generated values.

Ad
Log in to vote
-1
Answered by
DanzLua 2879 Moderation Voter Community Moderator
7 years ago

Well we could take another math.random() between 0 and 1, then if its 0 make the number *-1 if 1 nothing

local it = math.random()*0.5
local n = math.random(0,1)
if n==0 then it=it*-1 end
print(it)
0
Just to make sure, in this context does * = times? joshmatt2244 28 — 7y
0
@joshmatt2244 yes DanzLua 2879 — 7y
Log in to vote
-1
Answered by 7 years ago

You could just try subtracting 0.5 from math.random() * 1.

math.random()*1 - 0.5

Since the minimum value of math.random() is 0, the minimum value of math.random() - 0.5 will be -0.5. Since the maximum value is 1, if you subtract 0.5 from that you will get 0.5

In general if you want to get a random number between some range (-n, n) where n is some integer, the formula is:

math.random() * 2n - n

To change the range of that, just add or subtract some other number from that.

0
Not cool down voting everyone else's answer just to make yours on top DanzLua 2879 — 7y
0
What are you on about. I don't even have enough reputation to downvote. NotInventedHere 158 — 7y
0
my bad DanzLua 2879 — 7y
Log in to vote
-1
Answered by 7 years ago

Try

math.random (-0.5, 0.5)

Answer this question