Reputation: 267
Does anyone know how to generate random numbers from -1 to 1. Or is it even possible to do? I've researched already and i only get answers for generating random numbers from 0 to N. By the way, i'm using PHP.
Please help! Thanks in advance to those who'll answer!
Upvotes: 0
Views: 144
Reputation: 95101
You can try this for integers:
$array = range(- 1, 1, 1);
echo $array[mt_rand(0, count($array) - 1)]; // example 0
Or this for floats with precision declared in the third parameter of range()
:
$array = range(- 1, 1, 0.1);
echo $array[mt_rand(0, count($array) - 1)]; // example -0.9
Upvotes: 1
Reputation: 3129
Generate random number between 0 and 2, then subtract 1 from generated number.
Upvotes: 3
Reputation: 21773
If you have a random function that generates numbers from 0.0 to 1.0, multiply the result by two and subtract 1.
Upvotes: 4