python - 每次循环运行时都需要生成不同的随机数
问题描述
我需要在第二个 for 循环中生成一组不同的随机数。但是每次第二个 for 循环运行时,它都会生成相同的随机数集。
class pricing_lookback:
def __init__(self,spot,rate,sigma,time,sims,steps):
self.spot = spot
self.rate = rate
self.sigma = sigma
self.time = time
self.sims = sims
self.steps = steps
self.dt = self.time/self.steps
def call_floatingstrike(self):
pathwiseminS = np.array([])
simulationS = np.array([])
simulationSt = np.array([])
call2 = np.array([])
tst1 = np.array([])
for j in range(self.sims):
sT = self.spot
for i in range(self.steps):
phi= np.random.rand()
sT *= np.exp((self.rate-0.5*self.sigma*self.sigma)*self.dt + self.sigma*phi*np.sqrt(self.dt))
pathwiseminS = np.append(pathwiseminS, sT)
tst1 = np.append(tst1, pathwiseminS[1])
call2 = np.append(call2, np.max((pathwiseminS[self.steps-1]-self.spot),0))
simulationSt = np.append(simulationS,pathwiseminS[self.steps-1])
simulationS = np.append(simulationS,min(pathwiseminS))
call = np.average(simulationSt) - np.average(simulationS)
return call,call2, tst1
pricelookback = pricing_lookback(110,0.05,0.2,1,200,252)
clookback, call2, t1 = pricelookback.call_floatingstrike()
print(clookback,t1)
解决方案
正如@user3483203 指出的那样,您的错误在其他地方。所有变量在您的第二个 for 循环中都是随机的:变量phi
和sT
每个循环都是随机的。您将pathwiseminS[1]
(常量,非随机值)附加到tst1
或t1
每次是第一个元素或sT
. 你应该尝试刷新/清空pathwiseminS
(因为我认为这是你想要做的),像这样:
def call_floatingstrike(self):
simulationS = np.array([])
simulationSt = np.array([])
call2 = np.array([])
tst1 = []
for j in range(self.sims):
sT = self.spot
pathwiseminS = np.array([]) #notice the placement here
for i in range(self.steps):
phi= np.random.rand()
sT *= np.exp((self.rate-0.5*self.sigma*self.sigma)*self.dt + self.sigma*phi*np.sqrt(self.dt))
pathwiseminS = np.append(pathwiseminS, sT)
tst1 = np.append(tst1, pathwiseminS[1])
call2 = np.append(call2, np.max((pathwiseminS[self.steps-1]-self.spot),0))
simulationSt = np.append(simulationS,pathwiseminS[self.steps-1])
simulationS = np.append(simulationS,min(pathwiseminS))
call = np.average(simulationSt) - np.average(simulationS)
return call,call2, tst1
推荐阅读
- jquery - 将项目从模态拖到页面上
- c - 如何在自己的 SIGCHLD 的处理程序中获取设置进程的 PID?
- c++ - Qt 的事件循环线程是安全的还是原子的?处理 `QueuedConnection` 时如何同步?
- regex - 允许除 %\/# 之外的 PosixPrint 字符?: 并且字符串开头和结尾的空格除外
- bash - 如何拆分包含打印机 IP 地址和文本的文本文件以发送到该打印机
- iis - 当 .NET Core 托管包的版本落后于开发机器版本时会发生什么
- python-3.x - QgsDistanceArea computeSpheroidProject 返回 0, 0
- google-cloud-functions - 错误:WebhookClient.handleRequest 处没有请求意图的处理程序
- angular - 结合两个 RxJS Observables/Subscriptions 并遍历它们的数据
- python - lxml 包含相对路径