如何在VBA中调试平方根溢出

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

我是VBA的新秀,我在VBA中使用sqr()时遇到问题。每当我在VBA中使用Sqr()函数时,SigSqrdt = sigma * Sqr(dt)行上就会出现一个消息框“运行时错误'6'溢出”。而且我仅尝试模拟布朗运动。

Sub Simulating_Geometric_Brownian_Motion()
Dim T, S, mu, sigma, dt, SigSqrdt, LogS, drift, i, N
T = InputBox("Enter the length of the time period (T)")
N = InputBox("Enter the number of periods (N)")
S = InputBox("Enter the initial stock price (S)")
mu = InputBox("Enter the expected rate of return (mu)")
sigma = InputBox("Enter the volatility (sigma)")
dt = T / N
SigSqrdt = sigma * Sqr(dt)
drift = (mu - 0.5 * sigma * sigma) * dt
LogS = Log(S)
ActiveCell.Value = "Time"
ActiveCell.Offset(0, 1) = "stock price"
ActiveCell.Offset(1, 0) = 0  ' beginning time
ActiveCell.Offset(1, 1) = S 'beginning stock price
For i = 1 To N
ActiveCell.Offset(i + 1, 0) = i * dt
LogS = LogS + SigSqrdt * RandN()
ActiveCell.Offset(i + 1, 1) = Exp(LogS)
Next i
End Sub

Function RandN()
RandN = Application.NormSInv(Rnd())
End Function

样本输入:

T=1000, N=1000, S=10, mu=10, sigma=1
excel vba integer-overflow
1个回答
0
投票

您的代码运行起来非常慢,但是我使用您提供的参数不会产生任何错误。我在下面大大加快了速度:

Sub Simulating_Geometric_Brownian_Motion()

    Dim T, S, mu, sigma, dt, SigSqrdt, LogS, drift, i, N

    Application.ScreenUpdating = False

    T = InputBox("Enter the length of the time period (T)")
    N = InputBox("Enter the number of periods (N)")
    S = InputBox("Enter the initial stock price (S)")
    mu = InputBox("Enter the expected rate of return (mu)")
    sigma = InputBox("Enter the volatility (sigma)")
    dt = T / N
    SigSqrdt = sigma * Sqr(dt)
    drift = (mu - 0.5 * sigma * sigma) * dt
    LogS = Log(S)
    With ActiveCell
        .Value = "Time"
        .Offset(0, 1) = "stock price"
        .Offset(1, 0) = 0  ' beginning time
        .Offset(1, 1) = S 'beginning stock price
        For i = 1 To N
            .Offset(i + 1, 0) = i * dt
            LogS = LogS + SigSqrdt * RandN()
            .Offset(i + 1, 1) = Exp(LogS)
        Next i
    End With
    Application.ScreenUpdating = True

End Sub

Function RandN()
    RandN = Application.NormSInv(Rnd())
End Function

关于您收到的overflow错误,请尝试关闭Excel或重新启动计算机:)在极少数情况下,Excel或Windows实例实例损坏并产生奇怪的结果,尽管代码没有错。

© www.soinside.com 2019 - 2024. All rights reserved.