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?
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.
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)
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.