MATLAB and C language comparison example: random number generation
Author: Kailugaji - Blog Park http://www.cnblogs.com/kailugaji/
1. Integer random number generator function
1. C language program
int intrand(int lower,int upper) { double X = (double)rand() / RAND_MAX; return lower+(int)(X*(upper-lower)); }
2. MATLAB program
intrand.m
function y= intrand(lower,upper) % generate random numbers x =rand( 1 , 1 ); z=int32(x*(upper-lower)); y=lower+z; end
The result of running the matlab program:
>> y=intrand(0,10) y = 8
2. Double-precision random number generation
1. C language program
double doublerand(double lower,double upper) { double x = (double)rand() / RAND_MAX; return lower+x*(upper-lower); }
2. MATLAB program
doublerand.m
function y= doublerand(lower,upper) % Generate random number x =rand( 1 , 1 ); y=lower+x.*(upper-lower); end
The result of running the matlab program:
>> y=doublerand(0,10) y = 6.3236
Among them, the RAND_MAX of the C language is a character constant defined by the macro in stdlib.h:
#define RAND_MAX 0x7FFF
The minimum value is 32767 and the maximum value is 2147483647
Usually RAND_MAX can be used when generating random decimals.
If there are deficiencies in the function, please give me more advice.