Hi

Ive found lots tutorials detailing how to create random integer values, but I was wondering how to create random decimal values between a range?

Thanks for any help

TJJ

Printable View

- 04-26-2004TJJRandom Decimals
Hi

Ive found lots tutorials detailing how to create random integer values, but I was wondering how to create random decimal values between a range?

Thanks for any help

TJJ - 04-26-2004major_small
do something like this:

Code:`float number=(1+rand()%10000)/100.0;`

**rand()**part... take notice that in the formula**1+rand()%100;**, the 1+ just adds one to whatever comes out, and the %100 is just performing a modulo on whatever rand() comes out to be...

don't forget to put this somewhere near the beginning of your program:Code:`srand(time(0));`

- 04-26-2004XSquared
>float number=(1+rand()%10000)/100.0;

float number=(float)(1+rand()%10000)/100.0; - 04-26-2004Speedy5
No you don't need that float casting there because the number he's dividing (100.0) is already a float. Well, technically its a double so you'd have to make it 100.0F.

- 04-26-2004Hunter2
(1+rand()%10000) isn't a floating point number. Usually, when performing operations on mixed types, the result is an integer value; so yes, the typecast is necessary if only to eliminate ambiguity.

- 04-26-2004Speedy5
No: only one of the operands has to be a floating point value for the result to be floating point. The (1+rand()%10000) part yields an integer but the 100.0 is a floating point value. So when you divide, the result will be a floating point value.

- 04-26-2004Thantos
Or heck why not use the better approach of :

Code:`float floatrandom(float lowerbound, float upperbound)`

{

return ((float)rand() / RAND_MAX) * (upperbound - lowerbound) + lowerbound;

}

- 04-26-2004Hunter2
>>No: only one of the operands has to be a floating point value for the result to be floating point.

Since when? I'm pretty sure I recall encountering a bug caused by this, where I had one integer and one floating-point (I think I was trying to convert degrees to radians or vice versa), and the whole thing was converted to an integer and rounded down, causing some very funked out results.

I'll run a test though, maybe you're right.

**EDIT**

Grr, you're right :o Learn something new every day...