kiss.c

Go to the documentation of this file.
00001 /* 
00002  *   PURPOSE
00003  *      the kiss generator of G. Marsaglia
00004  *      generate random integers (uint) in [0, 2^32 - 1]
00005  *      the state is given by 4 integers (z, w, jsr, jcong)
00006  *
00007  *   NOTES
00008  *      The code was given by G. Marsaglia at the end of  a
00009  *      thread  concerning  RNG  in C in several newsgroups
00010  *      (whom sci.math.num-analysis) "My offer of RNG's for
00011  *      C  was an invitation to dance..."
00012  *
00013  *      Slight modifications by Bruno Pincon for inclusion in
00014  *      Scilab (added set/get state routines)
00015  *
00016  *      kiss is made of combinaison of severals  others but  
00017  *      they  are not interfaced at the scilab level.
00018  *
00019  *      Need that it is assumed that the 
00020  *         unsigned long arithmetic is the classic 32 bits 
00021  *         unsigned arithmetic modulo 2^32 (ie all is exact
00022  *         modulo 2^32) 
00023  *
00024  */
00025 #include <math.h>             /* to use floor    */
00026 
00027 #include "machine.h" 
00028 #include "sciprint.h"
00029 
00030 
00031 /* The Marsaglia 's macros : */
00032 #define znew  (z=36969*(z&65535)+(z>>16))
00033 #define wnew  (w=18000*(w&65535)+(w>>16))
00034 #define MWC   ((znew<<16)+wnew )
00035 #define CONG  (jcong=69069*jcong+1234567)
00036 #define SHR3  (jsr^=(jsr<<17), jsr^=(jsr>>13), jsr^=(jsr<<5))
00037 #define KISS  ((MWC^CONG)+SHR3)
00038 
00039 /*  the kiss 's state  (any int in [0,2^32-1] are OK ?) */
00040 static unsigned long z=362436069, w=521288629, jsr=123456789, jcong=380116160;
00041 
00042 unsigned long kiss()
00043 {
00044   return ( KISS );
00045 }
00046 
00047 extern void sciprint __PARAMS((char *fmt,...));
00048 
00049 int set_state_kiss(double g1, double g2, double g3, double g4)
00050 {
00051   if (g1 == floor(g1) && g2 == floor(g2) && 
00052       g3 == floor(g3) && g4 == floor(g4) &&  
00053       0.0 <= g1 && g1 <= 4294967295.0 &&
00054       0.0 <= g2 && g2 <= 4294967295.0 &&
00055       0.0 <= g3 && g3 <= 4294967295.0 &&
00056       0.0 <= g4 && g4 <= 4294967295.0 )
00057     {
00058           z = (unsigned long) g1;
00059           w = (unsigned long) g2;
00060         jsr = (unsigned long) g3;
00061       jcong = (unsigned long) g4;
00062       return ( 1 );
00063     }
00064   else
00065     {
00066       sciprint("\n\r bad seeds for kiss, must be integers in [0,2^32-1]\n\r");
00067       return ( 0 );
00068     }
00069 }
00070 
00071 void get_state_kiss(double g[])
00072 {
00073   g[0] = (double) z;
00074   g[1] = (double) w;
00075   g[2] = (double) jsr;
00076   g[3] = (double) jcong;
00077 }
00078 

Generated on Sun Mar 4 15:03:59 2007 for Scilab [trunk] by  doxygen 1.5.1