Skip to content Skip to sidebar Skip to footer

How Can I Randomly Generate A Number In The Range -0.5 And 0.5?

In javascript how do I randomly generate a number between -0.5 and 0.5? The following only seems to give positive numbers, and no negative numbers. Math.random(-0.15, 0.15)

Solution 1:

Quoting MDN on Math.random,

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive)

So, generate random numbers between 0 and 1 and subtract 0.5 from it.

Math.random() - 0.5

Note:Math.random() doesn't expect any parameters. So, you cannot specify any range.


If you want to generate random numbers between a range, use the example snippets in MDN,

// Returns a random number between min (inclusive) andmax (exclusive)
functiongetRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Demo with Range

functiongetRandomArbitrary(min, max) {
  returnMath.random() * (max - min) + min;
}


functionappendToResult(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));
}
<preid="result" />

This works because, the expression

Math.random() * (max - min) + min

will be evaluated in the following manner. First,

Math.random()

will be evaluated to get a random number in the range 0 and 1 and then

Math.random() * (max - min)

it will be multiplied with the difference between max and min value. In your case, lets say max is 0.35 and min is -0.35. So, max - min becomes 0.7. So, Math.random() * (max - min) gives a number in the range 0 and 0.7 (because even if Math.random() produces 1, when you multiply it with 0.7, the result will become 0.7). Then, you do

Math.random() * (max - min) + min

So, for your case, that basically becomes,

Math.random() * (0.35 - (-0.35)) + (-0.35)
(Math.random() * 0.7) - 0.35

So, if (Math.random() * 0.7) generates any value greater than 0.35, since you subtract 0.35 from it, it becomes some number between 0 and 0.35. If (Math.random() * 0.7) generates a value lesser than 0.35, since you subtract 0.35 from it, it becomes a number between -0.35 and 0.

Solution 2:

You can use Math.random() to get a number between 0 and 1 then reduce .5 to set the lower and upper bounds

Math.random() - .5

Post a Comment for "How Can I Randomly Generate A Number In The Range -0.5 And 0.5?"