简体   繁体   中英

#value! error on worksheetfunction.gammadist in excel VBA

I'm writing a code to find a fixed point to the equation:

1/N = xf(x)/(1-F(x)),

where x=p(1+phi) and f and F are the pdf and cdf of the gamma distribution and N is a positive integer.

The right hand side is known to be increasing in x for the gamma distribution, so there must be a unique solution.

I wrote the function:

Function find_pdstar_gamma(alpha As Double, beta As Double, phi As Double, N As Integer) As Double

Dim plow As Double
Dim pmid As Double
Dim ptop As Double
Dim parg As Double
Dim f As Double
Dim Fbar As Double
Dim z As Double

plow = 0
ptop = 1000
Do
    pmid = (ptop + plow) / 2
    parg = (1 + phi) * pmid
    f = WorksheetFunction.GammaDist(parg, alpha, beta, False)
    Fbar = (1 - WorksheetFunction.GammaDist(parg, alpha, beta, True)) 
    z = parg * f / Fbar - 1 / N
    If z > 0 Then
        ptop = pmid
    Else
        plow = pmid
    End If
Loop Until ((ptop - plow) / ptop) < 1e-08
find_pdstar_gamma = (ptop + plow) / 2

End Function

I get a #value! error when I run the function. Any idea where my error is?

I'm guessing that you're getting a run-time error 6, (overflow) or run-time error 11 (division by 0). This can actually be misleading, because it is actually a division by zero involving a Double can be reported as an overflow.

The first thing to do is check to make sure that your operator precedence is correct for this line of code:

z = parg * f / Fbar - 1 / N

This is evaluated as

z = ((parg * f) / Fbar) - (1 / N)

This means that if Fbar is ever zero (or a double suitably small enough), you'll get an error here.

The second thing to do is validate your inputs or add an error handler. That way you'll be able to get a more meaningful indication as to what is wrong.

I am going to answer this question: "Any idea where my error is?" I really have no earthly idea, but I know how to narrow it down. In referring to getting a #value error -- it seems that you are using it as a worksheet function. That may be the intended application, but it makes it difficult to debug. Instead - run it in the immediate window. In the VBE type something like

?find_pdstar_gamma(1, 3, 0.5, 100)

(but with the values of alpha, beta, etc. which are giving you grief). When you do this -- computation will stop with the offending line highlighted (if you hit the debug button in the error msgbox). This tells you where the error is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM