Search code examples
pythonexcelvbascipypoisson

ChiDist excel function in python


I have an excel function that i'm trying to replicate into python but struggling to replicate it. Here's the function (VBA):

Function Z(Lambda, conf) As Integer
Application.Volatile
Lambda = Application.Round(Lambda, 3)
Select Case Lambda
Case Is < 400
For i = 0 To 500
'        v = Application.Poisson(i, Lambda, True)
v = Application.ChiDist(2 * Lambda, 2 * i + 2)
    If v >= conf Then
        Z = i
        Exit Function
    End If
  Next
Case Else
    Z = Application.NormInv(conf, Lambda, Sqr(Lambda))
End Select
End Function

In Excel if i run =z(2,95%), i get z=5

I thought I could use:

from scipy import stats
stats.chi2.cdf

but not getting far with it.

Any help is highly appreciated!


Solution

  • Managed to get the function working in python - thanks @Warren Weckesser for the guidance on the chi2.sf.

    from scipy.stats import norm, chi2
    
     def z(lamda_calc, prob):
    
    if lamda_calc < 400:
      z_calc = [i for i in range (0,500) if chi2.sf(2 * lamda_calc, 2 * i + 2) >= 
      prob][0]  
    else:
      z_calc = int(norm.ppf(prob,lamda_calc,sqrt(lamda_calc)))
    return z_calc
    
    print
    print ("z:'", z(1.4, 0.98))