-
[physik/nlsop.git] / random.c
1 /*
2  * random functions
3  *
4  * author: hackbard@hackdaworld.dyndns.org
5  *
6  */
7
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <stdlib.h>
13
14 #include "random.h"
15
16 static int rand_fd;
17 static u32 *c_ptr,*b_ptr;
18
19 int rand_init(char *rf)
20 {
21  if(rf==NULL)
22  {
23   if((rand_fd=open("/dev/urandom",O_RDONLY))<0)
24   {
25    puts("cannot open /dev/urandom");
26    return -1;
27   }
28  } else
29  {
30   if((rand_fd=open(rf,O_RDONLY))<0)
31   {
32    printf("cannot open %s\n",rf);
33    return -1;
34   }
35  }
36  if((b_ptr=(u32 *)(malloc(BUFSIZE*sizeof(u32))))==NULL)
37  {
38   puts("failed allocating random buffer");
39   return -1;
40  }
41  c_ptr=b_ptr+BUFSIZE;
42  
43  return 1;
44 }
45
46 int rand_close(void)
47 {
48  close(rand_fd);
49  
50  return 1;
51 }
52
53 u32 get_rand(u32 max)
54 {
55  if(c_ptr>=b_ptr+BUFSIZE)
56  {
57   if(read(rand_fd,b_ptr,BUFSIZE*sizeof(u32))<BUFSIZE*sizeof(u32))
58   {
59    /* -> assume random file, end reached */
60    puts("warning, will read random file from beginning ...");
61    lseek(rand_fd,0,SEEK_SET);
62    read(rand_fd,b_ptr,BUFSIZE*sizeof(u32));
63   }
64   c_ptr=b_ptr;
65  }
66
67  return((u32)(*(c_ptr++)*(max*1.0/((long long unsigned int)URAND_MAX+1))));
68 }
69
70 u32 get_rand_lgp(u32 max,double a,double b)
71 {
72  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));
73 }
74