1
I did the following lcg (linear congruency generator) to draw unsigned int from 0x00000000
to 0xFFFFFFFF
uniformly. Just for testing, I used the seed equal to zero and raffling the first five numbers to see what comes out.
# include <stdio.h>
unsigned long long int state = 0 ;
unsigned int rnd() {
state *= 0x60BDC8431972EFA5ull ;
state += 0x4D268FBC9E53A107ull ;
return (unsigned int)( state >> 32 ) ;
}
int main(void) {
printf( "%u\n" , rnd() ) ;
printf( "%u\n" , rnd() ) ;
printf( "%u\n" , rnd() ) ;
printf( "%u\n" , rnd() ) ;
printf( "%u\n" , rnd() ) ;
return 0 ;
}
The result is this.
1294372796
3162674411
1090754839
3480286764
3255825657
To draw a number in single floating point format within the range [a,b]
i did the following function which simply divides the drawn integer by 0xFFFFFFFFu
to act as a draw of 0.0f
to 1.0f
and uses the result to make lerp of a
to b
.
float random( float a , float b ){
float f0t1 = rnd()/(float)(0xFFFFFFFFu) ;
return a * ( 1-f0t1 ) + f0t1 * b ;
}
Testing like this,
int main(void) {
printf( "%f\n" , random(0,1) ) ;
printf( "%f\n" , random(0,1) ) ;
printf( "%f\n" , random(0,1) ) ;
printf( "%f\n" , random(0,1) ) ;
printf( "%f\n" , random(0,1) ) ;
return 0 ;
}
the result is this.
0.301370
0.736368
0.253961
0.810317
0.758056
I mean, it makes a division that costs a lot. You can even convert it into multiplication, but isn’t there a faster way to calculate it? I imagine that with magic numbers you could handle binary float code efficiently and calculate, correct?