实数区间内随机数产生原理 - 图解分析
1 //产生[low,high]内的任意随机数,并返回 2 float randnum(float low,float high) 3 { 4 int ret_rnd = 0.0; 5 6 float integerf = 0.0; 7 float driftf = 0.0; 8 9 if (low >= high) 10 { 11 printf("low >= high,rearrange them "); 12 getchar(); 13 return; 14 } 15 //--------------------------------------------- 16 17 int integer; //整数部分 18 int decimals; //小数部分 19 20 float diff = high - low; 21 22 integer = (int)(high - low); //取整数部分 23 24 decimals = diff - integer; //取小数部分 25 //--------------------------------------------- 26 27 //1.先计算一个整数偏量值 28 if (integer > 0) 29 30 integerf= (float)(rand() % integer); 31 32 else 33 integerf= 0.0; 34 35 //2.在整数偏量的基础上进行波动 36 do 37 { 38 driftf = (float)(rand() / RAND_MAX);//产生小数 39 40 driftf *= (rand() % 2 == 0 ? 1 : -1); 41 42 } while ((integerf+driftf<0)||(integerf+driftf>diff)); 43 44 45 46 ret_rnd = low+(integerf + driftf) ; 47 48 return ret_rnd; 49 50 51 }
-------------------任意开区间,闭区间 随机数生成算法---------------
srand((unsigned)time(null));
- (a,b) (rand()%(b-a+1))+a-1
- [a,b) (rand()%(b-a))+a
- (a,b] (rand()%(b-a))+a+1
- [a,b] (rand()%(b-a+1))+a