in javascript how randomly generate number between -0.5 , 0.5? following seems give positive numbers, , no negative numbers.
math.random(-0.15, 0.15)
quoting mdn on math.random
,
the
math.random()
function returns floating-point, pseudo-random number in range [0, 1) is, 0 (inclusive) not including 1 (exclusive)
so, generate random numbers between 0 , 1 , subtract 0.5 it.
math.random() - 0.5
note: math.random()
doesn't expect parameters. so, cannot specify range.
if want generate random numbers between range, use example snippets in mdn,
// returns random number between min (inclusive) , max (exclusive) function getrandomarbitrary(min, max) { return math.random() * (max - min) + min; }
demo range
function getrandomarbitrary(min, max) { return math.random() * (max - min) + min; } function appendtoresult(value) { document.getelementbyid("result").innerhtml += value + "<br />"; } document.getelementbyid("result").innerhtml = ""; (var = 0; < 10; += 1) { appendtoresult(getrandomarbitrary(-0.35, 0.35)); }
<pre id="result" />
this works because, expression
math.random() * (max - min) + min
will evaluated in following manner. first,
math.random()
will evaluated random number in range 0 , 1 , then
math.random() * (max - min)
it multiplied difference between max
, min
value. in case, lets max
0.35
, min
-0.35
. so, max - min
becomes 0.7
. so, math.random() * (max - min)
gives number in range 0
, 0.7
(because if math.random()
produces 1
, when multiply 0.7
, result become 0.7
). then, do
math.random() * (max - min) + min
so, case, becomes,
math.random() * (0.35 - (-0.35)) + (-0.35) (math.random() * 0.7) - 0.35
so, if (math.random() * 0.7)
generates value greater 0.35
, since subtract 0.35
it, becomes number between 0
, 0.35
. if (math.random() * 0.7)
generates value lesser 0.35
, since subtract 0.35
it, becomes number between -0.35
, 0
.
Comments
Post a Comment