samedi 10 août 2019

Python and C returning different values for algorithm

I am trying to implement the following c code for a Tausworthe random number generator in python. The code needs to generate random numbers within the range of 0 to 1. The c code is as follows:

#include <stdint.h>
#include <stdio.h>


/**** VERY IMPORTANT **** :
  The initial seeds z1, z2, z3, z4  MUST be larger than
  1, 7, 15, and 127 respectively.
****/

#define SEED 987654321

static uint32_t z1 = SEED, z2 = SEED, z3 = SEED, z4 = SEED;


double lfsr113 (void)
{
   uint32_t b;
   b  = ((z1 << 6) ^ z1) >> 13;
   z1 = ((z1 & 4294967294U) << 18) ^ b;
   b  = ((z2 << 2) ^ z2) >> 27;
   z2 = ((z2 & 4294967288U) << 2) ^ b;
   b  = ((z3 << 13) ^ z3) >> 21;
   z3 = ((z3 & 4294967280U) << 7) ^ b;
   b  = ((z4 << 3) ^ z4) >> 12;
   z4 = ((z4 & 4294967168U) << 13) ^ b;
   return (z1 ^ z2 ^ z3 ^ z4) * 2.3283064365386963e-10;
}

So far I have implemented this in python as:

#Tausworthe implementation
#define seeds
s0 = 987654321
s1 = 987654321
s2 = 987654321
s3 = 987654321
b=0

def Taus():        

    global s0
    global s1
    global s2
    global s3
    global b

    b =  (((s0 << 6 )^s0) >>13)
    print(s0)
    s0 = (((s0 & 4294967294)<<18) ^ b)

    b =  (((s1 << 2) ^ s1) >>27)
    s1 = (((s1 & 4294967288) << 2) ^ b)
    b =  (((s2 << 13) ^ s2) >> 21)
    s2 = (((s2 & 4294967280) << 7) ^b)
    b  = ((s3 << 3) ^ s3) >> 12;
    s3 = ((s3 & 4294967168) << 13) ^ b;

    return((s0 ^ s1 ^ s2^s3)* 2.3283064365386963e-10)

When I run the C code I get the first three values generated as 0.920278, 0.277765 and 0.564335. When I run my python implementation I get the first three values as 60479.92110524047, 168598.21778273885, 1344.2269172724336.

I'm at a bit of a loss as to what I am doing wrong. The C implementation comes from the author of a paper on this specific Tausworthe generator and is therefore the correct one and when I run it produces the results I expect. I need to try and replicate these results in Python but I suspect the fact that C is strongly typed and that Python is not is maybe causing problems for me.

Any help or suggestions as to why my results are so off would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire