Original Post
🔒 Locked
Float number random
Advertisement
Hello. When you say "+ or - 0.5 of 12", you mean -6 to +6, right? To do this using rand:
float x = (rand()%1201)/100.0f - 6;
rand() gives you a number between 0 and RAND_MAX (a compiler-dependent constant).
rand() % 1201 gives you a number in the range 0-1200
Dividing by 100 gives you 0.00 to 12.00 (in 0.01 steps), and finally subtracting 6 puts you in -6 to 6 range.
I guess a general formula for a float in the range [a,b] in steps of n would be:
float x = (rand()%((b-a)/n+1)*n - a;
And you'd want to make sure the (b-a)/n + 1 is not bigger than RAND_MAX.
float x = (rand()%1201)/100.0f - 6;
rand() gives you a number between 0 and RAND_MAX (a compiler-dependent constant).
rand() % 1201 gives you a number in the range 0-1200
Dividing by 100 gives you 0.00 to 12.00 (in 0.01 steps), and finally subtracting 6 puts you in -6 to 6 range.
I guess a general formula for a float in the range [a,b] in steps of n would be:
float x = (rand()%((b-a)/n+1)*n - a;
And you'd want to make sure the (b-a)/n + 1 is not bigger than RAND_MAX.
Using modulo will only work with integers. This will achieve what you're after.....
If you call randf(0.1, 2, 0.5) the possible values will be 0.6, 1.1 and 1.6 (ie. the step size is from the min value). If you'd rather get the possible values 0.5, 1.0, 1.5, 2.0 then swap the order of the clip and offset lines.
float randf(float min=0.0f, float max=1.0f, float step=0.01f){ float r; r = rand() / (float)RAND_MAX; // Random number from 0.0->1.0 r = r*(max-min); // Scaled to range 0.0->(max-min) r = floor(r/step)*step; // Clip value to step size r = min + r; // Offset to range min->max return r;}If you call randf(0.1, 2, 0.5) the possible values will be 0.6, 1.1 and 1.6 (ie. the step size is from the min value). If you'd rather get the possible values 0.5, 1.0, 1.5, 2.0 then swap the order of the clip and offset lines.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement