From: hackbard Date: Tue, 13 May 2003 17:02:59 +0000 (+0000) Subject: initial checkin of random functions X-Git-Tag: fpb~62 X-Git-Url: https://hackdaworld.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=5d5a9a58e9ecb4221b1c41e536b9648500b9b41d;p=physik%2Fnlsop.git initial checkin of random functions --- diff --git a/random.c b/random.c new file mode 100644 index 0000000..17cbd73 --- /dev/null +++ b/random.c @@ -0,0 +1,73 @@ +/* + * random functions + * + * author: hackbard@hackdaworld.dyndns.org + * + */ + +#include +#include +#include +#include + +#include "random.h" + +static int rand_fd; +static u32 *c_ptr,*b_ptr; + +int rand_init(char *rf) +{ + if(rf==NULL) + { + if((rand_fd=open("/dev/urandom",O_RDONLY))<0) + { + puts("cannot open /dev/urandom"); + return -1; + } + } else + { + if((rand_fd=open(rf,O_RDONLY))<0) + { + printf("cannot open %s\n",rf); + return -1; + } + } + if((b_ptr=(u32 *)(malloc(BUFSIZE*sizeof(u32))))==NULL) + { + puts("failed allocating random buffer"); + return -1; + } + c_ptr=b_ptr+BUFSIZE; + + return 1; +} + +int rand_close(void) +{ + close(rand_fd); + + return 1; +} + +u32 get_rand(u32 max) +{ + if(c_ptr>=b_ptr+BUFSIZE) + { + if(read(rand_fd,b_ptr,BUFSIZE*sizeof(u32)) assume random file, end reached */ + puts("warning, will read random file from beginning ..."); + lseek(rand_fd,0,SEEK_SET); + read(rand_fd,b_ptr,BUFSIZE*sizeof(u32)); + } + c_ptr=b_ptr; + } + + return((u32)(*(c_ptr++)*(max*1.0/((long long unsigned int)URAND_MAX+1)))); +} + +u32 get_rand_lgp(u32 max,double a,double b) +{ + return((u32)(1.0*max*(-1.0*b+sqrt(b*b+2*a*((b+a/2)*get_rand(URAND_MAX)/((long long unsigned int)URAND_MAX+1))))/a)); +} + diff --git a/random.h b/random.h new file mode 100644 index 0000000..4fa9aae --- /dev/null +++ b/random.h @@ -0,0 +1,20 @@ +/* + * random functions - header + * + * author: hackbard@hackdaworld.dyndns.org + * + */ + +#include "nlsop.h" +#include +#include + +/* function prototypes */ +int rand_init(char *rf); +int rand_close(void); +int get_rand(u32 max); +int get_rand_lgp(u32 max,double a,double b); + +#define BUFSIZE (16*1048576) /* 64 MByte */ +#define URAND_MAX 0xffffffff +