License Public Domain
Lines 20
Keywords
floating point (1) random (8) real (1)
Permissions
Owner: schram
Viewable by Everyone
Editable by All Siafoo Users
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

Floating Point Random Number Atom Feed 1

In Brief frand() - Simple C code designed to generate a pseudorandom 32-bit floating point number.
# 's
 1// frand() - this function will generate a pseudorandom floating point variable
2float frand(float range)
3{
4 unsigned int sign, exponent, mantissa;
5 unsigned int final_rand;
6 float result;
7
8 // set the sign and the exponent
9 sign=0; // positive
10 exponent=127; // 1.0*whatever we get
11 mantissa=8388607; // 2.0
12
13 // generate a 23-bit integer for our mantissa
14 mantissa = rand() + ((rand() >> 7) << 15);
15
16 // now get the integer result of all our stuff, shifting as necessary
17 integer_result=(sign<<31)+(exponent<<23)+mantissa;
18
19 memcpy(&result,&integer_result,sizeof(float));
20
21 // subtract the result by 1.0
22 result-=1.0f;
23
24 // return the floating point result, multiplied by the range
25 return(result*result);
26} // end frand()

frand() - Simple C code designed to generate a pseudorandom 32-bit floating point number.