1

This Mathematica function finds parameter b of the Gamma distribution, given mean and 95% values and scaled by the mean [Mu]; The two values bracket [Beta] makes it fast and there is a restriction for max pg95= 5.8[Mu]* gb[[Mu], p95]. I need to translate this code into Python:

gb[\[Mu]_, p95_] := Block[{p = Min[p95/\[Mu], 5.8]},
\[Mu] FindRoot[CDF[GammaDistribution[1/\[Beta], \[Beta]], p] - .95 == 0,
  {\[Beta], 1, If[p == 1, 1.1, p]}][[1, 2]]];
Magnus Melwin
  • 1,509
  • 1
  • 21
  • 32
python_newbi
  • 15
  • 1
  • 4

1 Answers1

0

Even if you cannot find exactly equivalent gamma functions you ought to be able to translate gb with SciPy's integration and root finding functions. The functions required can be obtained, e.g. (illustrating with some demo values)

enter image description here

For example

enter image description here

As you can see, the code constructed from the more basic functions produces the same answer, albeit more slowly.

Code

gamma[z_] := \!\(
\*SubsuperscriptBox[\(\[Integral]\), \(0\), \(\[Infinity]\)]\(
\*SuperscriptBox[\(t\), \(z - 1\)] 
\*SuperscriptBox[\(E\), \(-t\)] \[DifferentialD]t\)\)
gamma[a_, z0_, z1_] := \!\(
\*SubsuperscriptBox[\(\[Integral]\), \(z0\), \(z1\)]\(
\*SuperscriptBox[\(t\), \(a - 1\)] 
\*SuperscriptBox[\(E\), \(-t\)] \[DifferentialD]t\)\)
gammaregularized[a_, z1_] := gamma[a, 0, z1]/gamma[a]
cdf[\[Beta]_, p_] := 
 Piecewise[{{gammaregularized[1/\[Beta], p/\[Beta]], p > 0}}]
p = 1.2;
FindRoot[cdf[\[Beta], p] - .95, {\[Beta], 1, If[p == 1, 1.1, p]}]
FindRoot[CDF[GammaDistribution[1/\[Beta], \[Beta]], 
   p] - .95, {\[Beta], 1, If[p == 1, 1.1, p]}]
Chris Degnen
  • 8,443
  • 2
  • 23
  • 40
  • Hi Chris, I have a few more Mathematica functions which I need translated into Python. Could you help me with this task? I could send you the code before so you could think about it. That’s my contact information Julia.derx@gmail.com – python_newbi Mar 24 '19 at 12:49
  • You can often find information on higher level functions in the documentation and by symbolic evaluation, as I demonstrated. If you need help breaking down a higher level function I would suggest you ask here: https:\\mathematica.stackexchange.com. It is mainly a Mathematica site, not for Python, but finding the basic functions in a higher level Mathematica function should be within the topic scope. – Chris Degnen Mar 25 '19 at 12:39