Chinaunix首页 | 论坛 | 博客
  • 博客访问: 788314
  • 博文数量: 83
  • 博客积分: 7030
  • 博客等级: 少将
  • 技术积分: 1097
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-06 15:50
文章分类

全部博文(83)

文章存档

2011年(2)

2010年(9)

2009年(56)

2008年(16)

我的朋友

分类: C/C++

2009-04-08 22:36:48

鉴于网络上有很多人想写自己的随机函数,但很多人都有自己的想法,比如用malloc出的地址作为种子,这样得出来的随机数总是递增的,不能体现“随机”,如下方法是自己的一个想法,跟大家分享。有什么问题或者有什么更好的想法,欢迎到http://voip01.cublog.cn , e-mail:happyyangxu@163.com留言。
如下是在TurboC下面调试过,通过屏幕打点可以看到随机数的随机性,性能非常不错,大家可以比较下系统提供的rand函数,测试哪个随机性好些!
运行的结果如下
 

#include<stdio.h>
#include<graphics.h>
#include<stdlib.h>
static unsigned long s_srand;
void my_srand(unsigned long value)
{
    static unsigned long a[] = {0x12345678,0x23456789,0x3456789a,0x456789ab,0x56789abc,0x6789abcd,0x789abcde,0x89abcdef};
    static unsigned long b[] = {0x87654321,0x98765432,0xa9876543,0xba987654,0xcba98765,0xdcba9876,0xedcba987,0xfedcba98};
    static unsigned char i = 0;
    unsigned char array_size = sizeof(a);
    if(value == 0)
    {
        s_srand = a[i];
        i = (++i)%array_size;
        return;
    }
    while(1)
    {
        s_srand = (a[i%array_size]+value) & 0xffffffff;
        a[i] = (b[i]+s_srand) & 0xffffffff;
        b[i] = (a[i]*s_srand) & 0xffffffff;
        i = (++i)%array_size;
        if (s_srand != 0)
            break;
    }
}
unsigned long my_rand()
{
    my_srand(1234+s_srand);
    return s_srand;
}
int main()
{
    int i;
    int gdriver=DETECT,gmode;
    initgraph(&gdriver,&gmode,"");
    setcolor(6);
    for( i = 0; i < 1000; i++)
    {
        /*printf("rand value:0x%08x\n",rand());*/
        putpixel(my_rand()%640,my_rand()%480,10);
        /*line(my_rand()%640,my_rand()%480,my_rand()%640,my_rand()%480);*/
    }
    getch();
    closegraph();
    return 1;
}


上面的代码里面的数学表达式没有认真的化简过,呵呵~~如果哪位老兄能把数学表达式弄出来就太强了~~

阅读(1268) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~