包含头文件
#include<ctime>
,利用srand()产生随机种子:
srand((unsigned)time(NULL));
利用rand()函数产生[0-a)的随机数
#define random(x) (rand()%x)
定义产生在[-x,x]之间浮动的值,x为浮点数:
zfloat_t randomDif(zfloat_t x, int32_t n)
{
int32_t precision = 10 ^ n;
int32_t y = static_cast<int32_t>(precision * x);
if (y == 0)
{
y+=1;
}
int32_t z = rand()%(2*y) - y;
return z / (1.0f * precision); // positive or negtive x
}
其中 n 为精度, 比如你希望产生正负0.0001范围内的数,那么n至少为4,由于精度问题,0.0001可能在计算的时候是0.0000999,这样n取4的话,y 的值就为0了,所以,这个时候你可以采取两个方式保护,要么n你取一个比较保险的值,至少为5,要么加除零保护,以上程序的保护只是临时保护,不够严谨,,,
部分测试程序如下:
zfloat_t channelR[81] = {0};
zfloat_t channelG[81] = {0};
zfloat_t channelB[81] = {0};
zfloat_t channelI[81] = {0};
int32_t count = 125;
int32_t constVal = 100;
zfloat_t difR = 10;
zfloat_t difG = 10.f;
zfloat_t difB = 10.f;
srand((unsigned)time(NULL)); // 随机种子
for (int32_t i = 0; i < count; i++, difG += 1, difB += 1)
{
for (int32_t j = 0; j < winSize; j++)
{
channelR[j] = constVal + randomDif(difR, 5);
channelG[j] = constVal + randomDif(difG, 5);
channelB[j] = constVal + randomDif(difB, 5);
channelI[j] = random(255);
}
}
当然还有其他实现方法。。。