每次循环运行时都需要生成不同的随机数

问题描述 投票:0回答:1

我需要在第二个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)
python numpy random
1个回答
0
投票

正如@ user3483203指出的那样,您的错误在其他地方。所有变量都在你的第二个for循环中随机化:变量phisT是每个循环随机的。您每次将pathwiseminS[1](常数,非随机值)附加到tst1t1,这是第一个元素,或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
© www.soinside.com 2019 - 2024. All rights reserved.