本帖最后由 suchocolate 于 2021-11-10 22:52 编辑
算上函数那10次,实际有100w次核心计算,numpy确实慢,帮你优化了一下代码,节省20%时间吧。import matplotlib.pyplot as plt
import numpy as np
import time
start = time.time()
np.random.seed(0)
x_ = np.linspace(0, 1, 101)
y_ = []
ps = x_[::-1] # 直接取反不用逐个计算
d = {0: 2, 1: 2, 2: -1} # 字典查询能够加速
for i, x in enumerate(x_):
p = [x, ps[i]]
w = 0
for j in range(1000):
for k in range(10):
c = np.random.choice([0, 1], p=p, size=2).sum() # 一次生成2个直接求和,p是普通列表页可以。
w += d[c]
y_.append(w)
end = time.time()
print(end-start)
plt.plot(x_, y_)
plt.show()
用普通random帮你写了一个,这个1秒多:import matplotlib.pyplot as plt
import time
import random
# 权重选择函数
def test(p):
result = 0
for m in range(2):
r = random.uniform(0, 1) # 随机一个浮点数
if r <= p[0]: # p中的概率也可以理解为权重,概率=权重/权重和,若权重某一轮为[0.2,0.8],若随机数小于等于0.2,那么本轮结果为0,反之为1。
result += 0
else:
result += 1
return result
start = time.time()
x_ = [x / 100.0 for x in range(101)]
y_ = []
ps = x_[::-1]
d = {0: 2, 1: 2, 2: -1}
for i, x in enumerate(x_):
p = {0: x, 1: ps[i]}
w = 0
for j in range(1000):
for k in range(10):
c = test(p)
w += d[c]
y_.append(w)
end = time.time()
print(end - start)
plt.plot(x_, y_)
plt.show()
前几天一位鱼友的提问也是权重选择:https://fishc.com.cn/thread-204828-1-1.html |