-
[physik/morpheus.git] / random.c
1 /*
2  * random.c - functions to get random values
3  *
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11
12 #include "defines.h"
13
14 /* global and extern variables */
15 extern u32 gr;
16 extern int random_fd;
17 extern u32 *rand_buf,*rand_current;
18 extern char random_file[MAX_CHARS_RANDOM_FILE];
19
20 /* return random integer between 0 - max-1 */
21 u32 rand_get(u32 max) 
22 {
23  if(rand_current>=rand_buf+(RAND_BUF_SIZE/sizeof(u32)))
24  {
25   printfd("debug: reading new random bytes\n");
26   if(read(random_fd,rand_buf,RAND_BUF_SIZE)!=RAND_BUF_SIZE)
27   {
28    if(!strcmp(random_file,""))
29    {
30     puts("random file end, starting over ...");
31     lseek(random_fd,0,SEEK_SET);
32    } else
33    {
34     puts("failed reading 1 mega bytes of random data");
35     return -23;
36    }
37   }
38   printfd("debug: finished reading random bytes\n");
39   rand_current=rand_buf;
40  }
41  /* cells numbered 0...max-1 */
42  return((u32)(*(rand_current++)*(max*1.0/URAND_MAX)));
43 }
44
45 /* get z value (linear growth of probability with depths) */
46 u32 rand_get_lgp(int slope,int start,u32 z_max)
47 {
48  int z;
49  u32 i,weighted_sum_z;
50  weighted_sum_z=z_max*start+slope*gr;
51  z=rand_get(weighted_sum_z)+1; /* +1 as rand_get returns values 0...max-1 */
52  for(i=1;;i++)
53  {
54   z-=(start+i*slope);
55   if(z<=0) break;
56  }
57  return(i-1); /* return values 0...z_cell-1 */
58 }
59