Random walk generate OverflowError: cannot convert float infinity to integer

Random walk generate OverflowError: cannot convert float infinity to integer

我从 this link 编辑了一段随机游走代码(ps:原来的有效):

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import random

days = 100 # time horizon
random.seed(2022)

def random_walk(startprice):
    price = np.zeros(days)
    
    x = np.round(np.random.uniform(0, 10, days))
    y = np.round(np.random.uniform(0, 10, days))
    
    price[0] = startprice
    for i in range(1, days):
        price[i] = (1 + 0.8*x[i] + 1.5*y[i])*price[i-1]
        # print(price[i])
    return price

fig, axn = plt.subplots(figsize=(10, 6))
for run in range(10):
    axn.plot(random_walk(10), label='time', linewidth='2')

但是我编辑的版本抛出了一个错误:OverflowError: cannot convert float infinity to integer,有人可以帮助解决这个问题吗?提前致谢。

嗯,x[i]可以大到10,y[1]也可以,所以

 (1 + 0.8*x[i] + 1.5*y[i])*price[i-1]

可以大到 (1 + 0.8*10 + 1.5*10)*price[i-1] = 24.0 * price[i-1].

你只需要几百个链接溢出到无穷大:

>>> import math
>>> math.nextafter(math.inf, 0)
1.7976931348623157e+308
>>> math.log(_, 24)
223.3387949931843

当然他们不会都是 10,但这并不重要:无论如何指数增长都会迅速爆发。例如,如果它们都是 5 个:

>>> math.log(1.7976931348623157e+308, 5)
441.0127954671545

更多的问题是为什么你期望它溢出到无穷大?

请注意,您开始的代码在每一步上都没有相乘。它 添加了 一个“随机冲击”。这样表现要好得多。