Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random number between [-1, 1] in C?

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?

like image 714
itsaboutcode Avatar asked Oct 12 '09 22:10

itsaboutcode


People also ask

How can we turn a random number between 0 to 1 into a random number between 1 and 1?

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.


1 Answers

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.

like image 100
Jacob Avatar answered Sep 24 '22 02:09

Jacob