I have seen many questions on SO about this particular subject but none of them has any answer for me, so I thought of asking this question.
I wanted to generate a random number between [-1, 1]. How I can do this?
The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.
Use -1+2*((float)rand())/RAND_MAX
rand()
generates integers in the range [0,RAND_MAX]
inclusive therefore, ((float)rand())/RAND_MAX
returns a floating-point number in [0,1]
. We get random numbers from [-1,1]
by adding it to -1
.
EDIT: (adding relevant portions of the comment section)
On the limitations of this method:
((float)rand())/RAND_MAX
returns a percentage (a fraction from 0 to 1). So since the range between -1 to 1 is 2 integers, I multiply that fraction by 2 and then add it to the minimum number you want, -1. This also tells you about the quality of your random numbers since you will only have RAND_MAX
unique random numbers.
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