我尝试使用Python执行以下代码:
我的代码如下:
#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")
与此同时,输出结果如下:
可以看到,程序能够运行,但不是很优化(大约需要1小时的运行时间)。
我该如何优化它以在几秒钟内获得所需的输出?
987654321*pow(663608941, 2**30, 0xFFFFFFFF)
怎么样? - Dummmy987654321* 663608941^(2**30) % 0xFFFFFFFF)
。0xFFFFFFFF
是32位整数的最大值。mod 0xFFFFFFFF
的目的是模拟32位整数的算术运算。pow
函数在内部使用模幂算法,比直接迭代算法更有效率。但正如 @r3mainer 所说,它不检查较短序列长度。因此可能偏离问题描述的要点。 - Dummmy987654321*pow(663608941, 2**30, 1<<32)
。 - Dummmy