initial checkin of random functions
authorhackbard <hackbard>
Tue, 13 May 2003 17:02:59 +0000 (17:02 +0000)
committerhackbard <hackbard>
Tue, 13 May 2003 17:02:59 +0000 (17:02 +0000)
random.c [new file with mode: 0644]
random.h [new file with mode: 0644]

diff --git a/random.c b/random.c
new file mode 100644 (file)
index 0000000..17cbd73
--- /dev/null
+++ b/random.c
@@ -0,0 +1,73 @@
+/*
+ * random functions
+ *
+ * author: hackbard@hackdaworld.dyndns.org
+ *
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#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))<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 (file)
index 0000000..4fa9aae
--- /dev/null
+++ b/random.h
@@ -0,0 +1,20 @@
+/*
+ * random functions - header
+ *
+ * author: hackbard@hackdaworld.dyndns.org
+ *
+ */
+
+#include "nlsop.h"
+#include <math.h>
+#include <stdio.h>
+
+/* 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
+