生成随机数字时出现types不匹配错误

当我生成随机数时,我有时会得到(并非总是)以下错误:

运行时错误“13”:types不匹配。

在线Z = Sqr(time) * Application.NormSInv(Rnd()) (和第二个for循环的结尾)。

为什么我得到这个错误?

我认为它与包含Rnd()的事实有关。

 Sub asiancall() 'defining variables Dim spot As Double Dim phi As Integer Dim rd_cont As Double Dim rf_cont As Double Dim lambda As Double Dim muY As Double Dim sigmaY As Double Dim vol As Double Dim implied_vol As Double Dim spotnext As Double Dim time As Double Dim sum As Double Dim i As Long Dim mean As Double Dim payoff_mean As Double Dim StDev As Double Dim K As Double Dim Egamma0 As Double Dim mulTv As Double Dim prod As Double Dim U As Double Dim Pois As Double Dim Q As Double Dim Z As Long Dim gamma As Double Dim payoff As Double Dim payoff_sum As Double Dim secondmoment As Double Dim j As Long Dim N As Long Dim mu As Double Dim sum1 As Double 'read input data spot = Range("B3") rd_cont = Range("C5") rf_cont = Range("C4") muY = Range("B17") sigmaY = Range("B18") lambda = Range("B16") K = Range("F33") implied_vol = Range("F35") N = Range("F34") vol = Range("B6") 'calculations sum_BS = 0 payoff_BS = 0 mean_BS = 0 secondmoment_BS = 0 For j = 1 To N spotnext = spot spotnext_BS = spot time = 0 sum1 = 0 time = 184 / (360 * 6) For i = 1 To 6 ' 'Merton uitvoeren Egamma0 = Exp(muY + sigmaY * sigmaY * 0.5) - 1 mu = rd_cont - rf_cont mulTv = (mu - lambda * Egamma0 - implied_vol * implied_vol * 0.5) * time sum = 0 prod = 1 Do While sum <= time U = Rnd() Pois = -Log(U) / lambda sum = sum + Pois Q = Application.NormInv(Rnd(), muY, sigmaY) gamma = Exp(Q) - 1 prod = prod * (1 + gamma) Loop prod = prod / (1 + gamma) Z = Sqr(time) * Application.NormSInv(Rnd()) spotnext = spotnext * Exp(mulTv + implied_vol * Z) * prod sum1 = sum1 + spotnext Next i mean = sum1 / 6 payoff = Application.Max(mean - K, 0) payoff_sum = payoff_sum + payoff secondmoment = secondmoment + payoff * payoff Next j 

跟进我发布的社区wiki答案 ,一个可能的解决scheme是这样的:

 Function RndExcludingZero() Do RndExcludingZero = Rnd() Loop While RndExcludingZero = 0 End Function 

用法:

 Z = Sqr(time) * Application.NormSInv(RndExcludingZero()) 

Rnd()返回值> = 0和<1。

在某些时候它必然返回0.当在Excel中给定0时, NormSInv返回#NUM!

Excel错误。*当通过Application.NormSInv(0)在VBA中调用时,它返回值为“错误2036”(相当于#NUM! Excel错误)的子types错误的变体。

这样的Variant / Errors不能被隐式强制为一个数值(这是*运算符所期望的),因此在这种情况下,你会得到types不匹配的错误。

Rnd()碰巧返回0时,你只会得到这个错误,这与你的观察一致,即错误只是偶尔发生。

用户3964075在这个问题的一个现在已经不存在的评论中首先提出这个问题。