how we generate uniform (0.0,1.1) double random numbers with seed function in c??

botool

Estimable
Dec 29, 2014
1
0
4,510
how we generate uniform (0.0,1.1) double random numbers with seed function in c

double rand_val(int seed)
{
z=((b-a)*rand()+a)*(2^32-1)/2^32)
};
 
Solution


Step 1: initialise the C-standard PRNG using srand(seed)

Step 2: Generate a random number between 0 and RAND_MAX. RAND_MAX will in most cases be the maximum of the compiler's int data type. Note that rand() returns a signed int data type, yet has an unsigned range.

Step 3: Convert the random int generated in step 2 to a double precision floating point number, as well as RAND_MAX to a double precision floating point number. It is important that this be done through a type-cast, not a pointer-cast.

Step 4: Divide the random number (as a double) by RAND_MAX (as a double) and then...

Pinhedd

Distinguished
Moderator


Step 1: initialise the C-standard PRNG using srand(seed)

Step 2: Generate a random number between 0 and RAND_MAX. RAND_MAX will in most cases be the maximum of the compiler's int data type. Note that rand() returns a signed int data type, yet has an unsigned range.

Step 3: Convert the random int generated in step 2 to a double precision floating point number, as well as RAND_MAX to a double precision floating point number. It is important that this be done through a type-cast, not a pointer-cast.

Step 4: Divide the random number (as a double) by RAND_MAX (as a double) and then multiply the result by the difference between the upper and lower limits (1.1 - 0.0 for example) and then add the lower limit (0.0)

double rand_val(int seed, double lower, double upper)
{
int rand_int = 0;
double rand_float = 0, max_float = 0, result = 0;
srand(seed);
rand_int = rand();
rand_float = (double)rand_int;
max_float = (double)RAND_MAX;
result = (rand_float/max_float) * (upper - lower) + lower;
return result;
}

I haven't tested it, but it should work.

Note that this will not return a perfectly uniform range of values, that is very hard to do and is best done in hardware. Most PRNGs are satisfied with returning an approximately uniform range of values as this is much faster.
 
Solution