Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Random Positive or Negative Number

I need to create a random -1 or 1 to multiply an already existing number by. Issue is my current random function generates a -1, 0, or 1. What is the most efficient way of doing this?

like image 865
Ash Blue Avatar asked Dec 23 '11 02:12

Ash Blue


People also ask

How do you know if a number is positive or negative JavaScript?

The Math. sign() is a builtin function in JavaScript and is used to know the sign of a number, indicating whether the number specified is negative or positive.

How do you show negative numbers in JavaScript?

To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.

How do you generate a negative random number in Java?

The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .

How does random number work in JavaScript?

The Math. random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.


Video Answer


1 Answers

Don't use your existing function - just call Math.random(). If < 0.5 then -1, else 1:

var plusOrMinus = Math.random() < 0.5 ? -1 : 1; 
like image 155
ziesemer Avatar answered Sep 21 '22 10:09

ziesemer