4

I'm fairly new to Python but would like to use Euler's Gamma Function in a function I am writing. I'd prefer not to write it as an integral and was wondering if there's something I can import that easily defines the gamma function.

Thanks

Lanier Freeman
  • 273
  • 2
  • 3
  • 6
  • 1
    If you want an arbitrary precision gamma function, take a look at [mpmath](http://mpmath.org/doc/current/functions/gamma.html). – PM 2Ring Nov 04 '16 at 17:10
  • Looks like its in the standard library. `from math import gamma; gamma(10);` – Asad Saeeduddin Nov 04 '16 at 17:11
  • @AsadSaeeduddin Sure (if you have Python 2.7 or later). But unlike the mpmath version it doesn't handle complex numbers (and there's no gamma in cmath) and of course it's not arbitrary precision. – PM 2Ring Nov 05 '16 at 08:33

4 Answers4

10

Yes, you can. In the module math there are special functions coded such as the Gamma function.

Look at here

MMF
  • 5,750
  • 3
  • 16
  • 20
9

I'd use scipy.special.gamma().

Batman
  • 8,571
  • 7
  • 41
  • 80
  • 3
    Important note: `scipy.special.gamma()` takes arbitrary np.arrays as input. `math.gamma()` requires float or single-element numpy arrays, which a crippling limitation in many use cases. – Mark_Anderson Jul 15 '20 at 19:53
2

There is another way:

from mpmath import gamma
print(float(gamma(0.5)))

1.772453850905516

Tech Expert Wizard
  • 365
  • 1
  • 6
  • 21
USERNAME GOES HERE
  • 692
  • 1
  • 15
  • 29
-2

If you want to go deep with Python and other methods I'll recommend that you look at numpy and scipy libraries.

A gamma function can be as easy as

from scipy.stats import gamma
a = 1.99323054838
rv = gamma(a)

That's it, check https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma for more info and https://www.scipy.org/ if you want to know more about scientific computing with python.

Tenoch G
  • 171
  • 3