-3

How can this return a number between -2 and 2

var number = Math.random() * 4 - 2;
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
Hayk
  • 187
  • 1
  • 10

1 Answers1

1

The method Math.random() gives you a decimal number between 0 and 1. If it returns, 0.00001, you'll get 0.00001 * 4 - 2 = 0.00004 - 2 = -1.99996

A 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.

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149