Mateusz
Mateusz

Reputation: 331

How to get random 1 or -1 in canvas (javascript)?

How can I get random -1 or 1 (not between -1 or 1, just -1 or 1, only this 2 values) in canvas?

I know that to get random number I can use:

Math.random()

But I want only random 1 or -1.

Upvotes: 0

Views: 649

Answers (4)

Lazyexpert
Lazyexpert

Reputation: 3154

Just in a case someone doesn't get how the ternar operator works, ill write the same in the other way:

var value;
if(Math.random() > 0.5) value = 1;
else value = -1;

ups, fixed coma. thx.

Upvotes: 1

GameAlchemist
GameAlchemist

Reputation: 19294

Solution that does not use branching :

((Math.random()+0.5)<<1)-1

This solution uses a formula that matches the [0, 1] interval into the {-1, 1} set.
Here i used floor to do so.

Let's see how : If i add 0.5 to Math.random() i'm now in [0.5, 1.5].
After flooring the result is in the {0, 1} set.
Now you multiply by two => { 0, 2} set.
Now remove 1 => {-1, 1} set.

So the formula is this one :

2*Math.floor(Math.random()+0.5)-1

Faster (but more cryptic :-) ) using the shift operator :

((Math.random()+0.5)<<1)-1

Unfortunately... branching is faster as you can see here (look in the console).

https://jsfiddle.net/h6d8bthd/

Upvotes: -1

custi
custi

Reputation: 563

var plusOrMinus = Math.random() < 0.5 ? -1 : 1;

(please use the search first JavaScript Random Positive or Negative Number)

Upvotes: 4

markE
markE

Reputation: 105035

You could do this:

var n = (Math.random()>=0.50)?1:-1;

Upvotes: 2

Related Questions