How can I randomly generate a number between -0.5 and 0.5?
In javascript, how do I randomly generate a number between -0.5 and 0.5? The following only give positive numbers and negative numbers.
Math.random(-0.15, 0.15)
Quoting MDN on Math.random
.
The function
Math.random()
returns a pseudo-random floating point number in the range [0, 1), which ranges from 0 (inclusive) to, but not including 1 (excluding)
So, create random numbers between 0 and 1 and subtract 0.5 from it.
Math.random() - 0.5
Note. Math.random()
does not expect any parameters. Thus, you cannot specify a range.
If you want to generate random numbers between a range use the snippet examples on MDN.
// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
Demo with range
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function appendToResult(value) {
document.getElementById("result").innerHTML += value + "<br />";
}
document.getElementById("result").innerHTML = "";
for (var i = 0; i < 10; i += 1) {
appendToResult(getRandomArbitrary(-0.35, 0.35));
}
<pre id="result" />
This works because the expression
Math.random() * (max - min) + min
will be evaluated as follows. Firstly,
Math.random()
will evaluate to get a random number between 0 and 1 and then
Math.random() * (max - min)
it will be multiplied by the difference between the value max
and min
. In your case, say max
- 0.35
, and min
- -0.35
. So it max - min
becomes 0.7
. So, Math.random() * (max - min)
gives a number in the range 0
and 0.7
(because even if it Math.random()
does 1
, when you multiply it by 0.7
, the result will be 0.7
). Then you do
Math.random() * (max - min) + min
So, for your case, what basically becomes,
Math.random() * (0.35 - (-0.35)) + (-0.35)
(Math.random() * 0.7) - 0.35
So, if it (Math.random() * 0.7)
generates any value greater than 0.35
since you subtract from it 0.35
, it becomes some number between 0
and 0.35
. If it (Math.random() * 0.7)
generates a value less 0.35
as you subtract from it 0.35
, it becomes a number between -0.35
and 0
.
You can use Math.random()
to get a number between 0 and 1, then decrease .5
to set the lower and upper bounds
Math.random() - .5