How can i generate float random values in C? (also negative)
Share
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.
In general to generate random numbers from an arbitrary distribution you’d first generate uniform random numbers and then pass them to the inverse of the cumulative distribution function.
Assume for example that you want random numbers with uniform distribution on the interval [-10.0, 10.0] and all you’ve got is random numbers from [0.0, 1.0]. Cumulative distribution function of the uniform distribution on [-10.0, 10.0] is:
This expresses the probability that a random number generated is smaller than x. The inverse is
(You can obtain this easily on paper by switching the x and y axis).
Hence to obtain random numbers uniformly distributed on [-10.0, 10.0] you can use the following code:
In fact, you don’t need uniform0to1Random() since there are already a lot of good uniform random numbers generators from [0.0, 1.0] (e.g. in the boost library).
You can use the method to generate random numbers with nearly any probability distribution you want by sampling the inverse cumulative distribution as shown above.
See http://en.wikipedia.org/wiki/Inverse_transform_sampling for more details.