我正在运行一个Python模拟程序,用于预测一种加权和普通骰子。我想使用numba来帮助加快我的脚本速度,但是我收到了一个错误:
<timed exec>:6: NumbaWarning:
Compilation is falling back to object mode WITH looplifting enabled because Function "roll" failed type inference due to: Untyped global name 'sum': cannot determine Numba type of <class 'builtin_function_or_method'>
File "<timed exec>", line 9:
<source missing, REPL/exec in use?>
这是我的原始代码:是否有其他类型的numba表达式可以使用?目前我正在测试使用2500次投掷的输入;希望将其缩短到4秒钟(目前为8.5秒)。
%%time
from numba import jit
import random
import matplotlib.pyplot as plt
import numpy
@jit
def roll(sides, bias_list):
assert len(bias_list) == sides, "Enter correct number of dice sides"
number = random.uniform(0, sum(bias_list))
current = 0
for i, bias in enumerate(bias_list):
current += bias
if number <= current:
return i + 1
no_of_rolls = 2500
weighted_die = {}
normal_die = {}
#weighted die
for i in range(no_of_rolls):
weighted_die[i+1]=roll(6,(0.15, 0.15, 0.15, 0.15, 0.15, 0.25))
#regular die
for i in range(no_of_rolls):
normal_die[i+1]=roll(6,(0.167, 0.167, 0.167, 0.167, 0.167, 0.165))
plt.bar(*zip(*weighted_die.items()))
plt.show()
plt.bar(*zip(*normal_die.items()))
plt.show()