0

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!

1
  • 2
    There can't be negative random numbers. EVER. You'll open a stargate portal to hell and we'll just die. Seriously. Commented Apr 15, 2013 at 11:46

3 Answers 3

4

If you have a random function that generates numbers from 0.0 to 1.0, multiply the result by two and subtract 1.

Sign up to request clarification or add additional context in comments.

Comments

3

Generate random number between 0 and 2, then subtract 1 from generated number.

1 Comment

Oh I haven't realized that, and now i think it's the most practical thing to do.Thank you! That will do.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.