Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pseudo random number generator in python

Tags:

python

random

I tried to perform the following code using python:

enter image description here

My code is:

#UNIFORM RANDOM SAMPLING 

import numpy as np                #library needed for numerical calculations
import matplotlib.pyplot as plt   #library needed for plotting purposes
from time import process_time     #function needed for checking CPU time
from scipy.stats import chisquare #function needed for chi square test

#*******************************************************************************

i=np.uintc(987654321)              #unsigned int variable i with seed 987654321

r=2**30                            #range of the sequence

t1_start=process_time()            #process start time 

for count in range(r):             #for cycle over expected period and update i

    i=np.uintc(i*663608941)

t1_stop=process_time()             #process stop time
    
print("\nLoop stopped at the element:", i, ".\n")     
print("Is this the last element of the series? 1 for YES other numbers for NO", i/987654321,".\n")
print("The CPU time needed in order to take to go throught the whole sequence is", t1_stop-t1_start, "seconds.\n")

Meanwhile the output:

enter image description here

As you can see, the programm woks, but is not very optimized ( almost 1 hour of run).

How can I optimize it and obtain the desired output in many seconds?

like image 394
J.Snowden Avatar asked Feb 03 '26 19:02

J.Snowden


1 Answers

Do you have to use Python?

The code will run much faster in C. When compiled with -O3 optimization, this takes about a second to run on my desktop:

#include <stdio.h>
#include <inttypes.h>

int main() {
    uint32_t i, n;
    i = 987654321;
    n = 0;
    while (1) {
        n++;
        i *= 663608941;
        if (i == 987654321) break;
    }
    printf("Sequence repeats after %" PRIu32 " iterations.\n", n);
    printf("Expected value: %d.\n", 1<<30);
    return 0;
}

I should also point out that your code isn't strictly correct. It confirms that the sequence returns to its initial state after 230 iterations, but doesn't check for other occurrences of i=987654321 during the loop.


If you're stuck using Python, it looks like numpy's integer types don't offer much of an advantage in terms of speed. The following code runs in about 200 seconds on my machine.:

def seq_check():
    x = 987654321
    n = 0
    while True:
        n += 1
        x = (x * 663608941) & 0xffffffff
        if x == 987654321:
            break
    return n
like image 128
r3mainer Avatar answered Feb 05 '26 09:02

r3mainer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!