vendredi 20 février 2015

Different values using random function in VBA

I am writing a MonteCarlo simulation code.


I have a problem with the random numbers!


When i write



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


The average of the result is 0,25. When i change the randomize outside the loop:



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


Moreover, when i write the random numbers in the Excel worksheet and look up those numbers in the Macro, the average is like the second one (the Randomize outside the loop).


Anyone know why that is happening and which one is the correct code?





Aucun commentaire:

Enregistrer un commentaire