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?
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.
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.
The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With