在VBA中使用随机函数的不同值

时间:2015-02-20 16:43:38

标签: excel vba excel-vba random simulation

我正在编写一个MonteCarlo模拟代码。

我的随机数有问题!

我写的时候

Sub Simular()

Dim i As Integer
Dim j As Integer
Dim simulacion As Integer
Dim iterar As Double
Dim mu As Double
Dim varianza As Double
Dim aleat As Double
Dim cantidad As Double
Dim fecha As Date
simulacion = Sheet8.Cells(2, 3)

mu = Sheet8.Cells(7, 3)
varianza = Sheet8.Cells(8, 3)
cantidad = Sheet8.Cells(10, 3)
fecha = WorksheetFunction.WorkDay(Sheet8.Cells(4, 2), cantidad)
Sheet8.Cells(15, 4) = fecha
Sheet8.Cells(1, 2) = cantidad
Sheet8.Cells(3, 3) = Sheet8.Cells(1, 3)

For j = 1 To simulacion
precio = Sheet8.Cells(15, 3)
iterar = Sheet8.Cells(15, 3)
   For i = 1 To cantidad
   Randomize
   aleat = Rnd()
   iterar = iterar * Exp((mu - 1 / 2 * varianza) +       WorksheetFunction.Power(varianza, 0.5) * WorksheetFunction.Power(1, 0.5) *   WorksheetFunction.Norm_Inv(aleat, 0, 1))

   Next i
Sheet8.Cells(17 + j, 4) = iterar
Next j
End Sub

结果的平均值为0.25。当我在循环外更改随机化时:

Sub Simular()
Randomize
Dim i As Integer
Dim j As Integer
Dim simulacion As Integer
Dim iterar As Double
Dim mu As Double
Dim varianza As Double
Dim aleat As Double
Dim cantidad As Double
Dim fecha As Date
simulacion = Sheet8.Cells(2, 3)

mu = Sheet8.Cells(7, 3)
varianza = Sheet8.Cells(8, 3)
cantidad = Sheet8.Cells(10, 3)
fecha = WorksheetFunction.WorkDay(Sheet8.Cells(4, 2), cantidad)
Sheet8.Cells(15, 4) = fecha
Sheet8.Cells(1, 2) = cantidad
Sheet8.Cells(3, 3) = Sheet8.Cells(1, 3)

For j = 1 To simulacion
precio = Sheet8.Cells(15, 3)
iterar = Sheet8.Cells(15, 3)
  For i = 1 To cantidad
  aleat = Rnd()
  iterar = iterar * Exp((mu - 1 / 2 * varianza) + WorksheetFunction.Power(varianza, 0.5) * WorksheetFunction.Power(1, 0.5) * WorksheetFunction.Norm_Inv(aleat, 0, 1))
  Next i
Sheet8.Cells(17 + j, 4) = iterar
Next j
End Sub

此外,当我在Excel工作表中编写随机数并在宏中查找这些数字时,平均值就像第二个(循环外的Randomize)。

任何人都知道为什么会这样,哪一个是正确的代码?

0 个答案:

没有答案