How to generate random float number in C -
possible duplicate:
c++ random float
how generate random number in c?
i can't find solution find random float number [0,a]
, a
float defined user.
i have tried following, doesn't seem work correctly.
float x=(float)rand()/((float)rand_max/a)
try:
float x = (float)rand()/(float)(rand_max/a);
to understand how works consider following.
n = random value in [0..rand_max] inclusively.
the above equation (removing casts clarity) becomes:
n/(rand_max/a)
but division fraction equivalent multiplying said fraction's reciprocal, equivalent to:
n * (a/rand_max)
which can rewritten as:
a * (n/rand_max)
considering n/rand_max
floating point value between 0.0 , 1.0, generate value between 0.0 , a
.
alternatively, can use following, breakdown showed above. prefer because clearer going on (to me, anyway):
float x = ((float)rand()/(float)(rand_max)) * a;
note: floating point representation of a
must exact or never hit absolute edge case of a
(it close). see this article gritty details why.
sample
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char *argv[]) { srand((unsigned int)time(null)); float = 5.0; (int i=0;i<20;i++) printf("%f\n", ((float)rand()/(float)(rand_max)) * a); return 0; }
output
1.625741 3.832026 4.853078 0.687247 0.568085 2.810053 3.561830 3.674827 2.814782 3.047727 3.154944 0.141873 4.464814 0.124696 0.766487 2.349450 2.201889 2.148071 2.624953 2.578719
Comments
Post a Comment