What is the best way to generate a random float in C#?
Update: I want random floating point numbers from float.Minvalue to float.Maxvalue. I am using these numbers in unit testing of some mathematical methods.
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.
Best approach, no crazed values, distributed with respect to the representable intervals on the floating-point number line (removed “uniform” as with respect to a continuous number line it is decidedly non-uniform):
(*) … check here for subnormal floats
Warning: generates positive infinity as well! Choose exponent of 127 to be on the safe side.
Another approach which will give you some crazed values (uniform distribution of bit patterns), potentially useful for fuzzing:
An improvement over the previous version is this one, which does not create “crazed” values (neither infinities nor NaN) and is still fast (also distributed with respect to the representable intervals on the floating-point number line):
Least useful approach:
Floating point number line from: Intel Architecture Software Developer’s Manual Volume 1: Basic Architecture. The Y-axis is logarithmic (base-2) because consecutive binary floating point numbers do not differ linearly.