Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.random() help get '+N' and '-N' randoms ( excluding specific range )

I need a little help with Math.random():
I have to rotate some images (with CSS3 transform (deg) )
in the way to get results from -40 to +40
but skipping results from range: -20 and +20

math random defined + - radius

If I'm not wrong this will get me random results in a range from -40 to +40

  var counter = Math.round(Math.random()*81)-40;

How to exclude from the results numbers between -20 and +20 ???

like image 453
Roko C. Buljan Avatar asked Aug 16 '11 17:08

Roko C. Buljan


People also ask

What does math random () do?

The Math. random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.

Is math random really random?

It may be pointed out that the number returned by Math. random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets. However, the pseudo-random number generated by Math.

What does math random () 0.5 do?

random() - 0.5) , returns with equal probability that the first number is greater than the second, or vice versa, which makes the shuffle work much better.

Can you get 1 from math random?

A random number generator always returns a value between 0 and 1, but never equal to one or the other. Any number times a randomly generated value will always equal to less than that number, never more, and never equal. Math. floor(Math.


2 Answers

Random -1 or 1 times 0-20 random plus 20, could work

(Math.random()<.5?-1:1)*Math.floor(Math.random()*20 + 21);

Sample Results from 1300 runs (showing only positive for simplicity):

Number_21: 70
Number_22: 62
Number_23: 56
Number_24: 57
Number_25: 79
Number_26: 57
Number_27: 64
Number_28: 60
Number_29: 57
Number_30: 67
Number_31: 63
Number_32: 81
Number_33: 81
Number_34: 65
Number_35: 59
Number_36: 59
Number_37: 62
Number_38: 71
Number_39: 52
Number_40: 78
like image 136
Joe Avatar answered Oct 19 '22 23:10

Joe


I would have a random number between 20 and 40 generated, then randomly negate it.

var counter = (Math.round(Math.random() * 20) + 20) * (Math.random() < 0.5 ? 1 : -1);
like image 39
Alex Turpin Avatar answered Oct 20 '22 01:10

Alex Turpin