- Home /
Random between -1 and 1
I am trying to get a random float between -1 (inclusive) and 1 (inclusive).
I have tried Random.Range(-1, 1), but this just provides -0.1 or 0.
I have tried Random.Range(-1.0F, 1.0F), but this just provides between -0.1 and 0.1
Two questions:
Why are these the results? How can I get a random float between -1 and 1?
Details:
I am just calling the Random methods in my update method and printing them out like such:
void Update(){
float randomNumber = Random.Range(#, #) * 1;
Debug.log(randomNumber);
}
Update:
It is not happening unless I multiply by 1...what???
I have tried Random.Range(-1.0F, 1.0F), but this just provides between -0.1 and 0.1
That's untrue; it returns -1.0 through 1.0. Also, multiplying anything by 1 is just itself, so don't bother doing that (the compiler probably optimizes that out anyway).
Answer by Bunny83 · Nov 14, 2014 at 04:19 AM
Uhm, if i use your code (once fixed all typing errors) i get values between -1 and 1. Of course you have to use the float variant of the Range method, otherwise it will use the integer overload.
float randomNumber = Random.Range(-1f,1f);
Debug.Log(randomNumber);
So i can't reproduce your results.
btw: Random.Range(-1, 1) will only output two values: -1 and 0 as in this case you don't use the float overload but the integer overload which is $$anonymous$$ inclusive and max exclusive and will only return integer values.
It is different when you multiply randomNumber by 1, oddly enough
float one = 1;
float randomNumber = Random.Range(-1f,1f) * one;
Debug.Log(randomNumber);
And sorry for having typos above. I was unaware
@$$anonymous$$: Uhm, no i can't reproduce this neither. I always get values between -1f and 1f, no matter if i multiply it with 1, 1f or a float variable containing 1f. Are you sure you execute the correct testing code? In general it's not recommended to just Log a single number. It could come from a different test you did (and forgot) and your actual test isn't executed at all. You should always do something like:
Debug.Log("Random.Range(-1f,1f) = " + randomNumber);
That way you can be sure that the debug log actually comes from this piece of code.
Well, clicking on the debug output in the console will take you to the line of code that printed the log.
Well I am not sure what is going on if you are unable to reproduce. I must have some well hidden bug. Either way, I got it working now by changing 1 to 1.0F...soooo thanks :)
Answer by Dragonsnare0 · Nov 14, 2014 at 05:56 AM
Random.value gives you a random point between 0 - 1. Try
Random.value*2-1
There you go. random from -1 to 1
Your answer
![](https://koobas.hobune.stream/wayback/20220613171453im_/https://answers.unity.com/themes/thub/images/avi.jpg)