I can’t find any solution to generate a random float number in the range of [0,a], where a is some float defined by a user.
I have tried the following, but it doesn’t seem to work correctly.
float x=(float)rand()/((float)RAND_MAX/a)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try:
To understand how this works consider the following.
The above equation (removing the casts for clarity) becomes:
But division by a fraction is the equivalent to multiplying by said fraction’s reciprocal, so this is equivalent to:
which can be rewritten as:
Considering
N/RAND_MAXis always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 anda.Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):
Note: the floating point representation of
amust be exact or this will never hit your absolute edge case ofa(it will get close). See this article for the gritty details about why.Sample
Output