Skip to main content
gamedev.net
🔒 Locked

Float number random

Started by jammy5202 Apr 8, 2006 at 5:46 AM 3 replies 1k views
Original Post
jammy5202
jammy5202
I am trying to procduce a decimal number this is + or - 0.5 of 12 in steps of 0.01. I have tried using rand but does give correct results. What way is there to produce a result like this? thanks james
captainmikey
captainmikey
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.
jammy5202
jammy5202
Sorry i need i range from 11.5 to 12.5 with 0.01 steps
joanusdmentia
joanusdmentia
Using modulo will only work with integers. This will achieve what you're after.....

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.
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The nly verdict is vengeance; a vendett o

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.