How can I randomly generate a number in the range -0.5 and 0.5?

最后都变了- 提交于 2021-02-05 05:51:28

问题


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)

回答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) 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 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.




回答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


来源:https://stackoverflow.com/questions/30115860/how-can-i-randomly-generate-a-number-in-the-range-0-5-and-0-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!