Best way to write a Python function that integrates a gaussian?

前端 未结 5 1184
小鲜肉
小鲜肉 2021-02-04 18:48

In attempting to use scipy\'s quad method to integrate a gaussian (lets say there\'s a gaussian method named gauss), I was having problems passing needed parameters to gauss and

5条回答
  •  难免孤独
    2021-02-04 19:14

    Why not just always do your integration from -infinity to +infinity, so that you always know the answer? (joking!)

    My guess is that the only reason that there's not already a canned Gaussian function in SciPy is that it's a trivial function to write. Your suggestion about writing your own function and passing it to quad to integrate sounds excellent. It uses the accepted SciPy tool for doing this, it's minimal code effort for you, and it's very readable for other people even if they've never seen SciPy.

    What exactly do you mean by a fixed-width integrator? Do you mean using a different algorithm than whatever QUADPACK is using?

    Edit: For completeness, here's something like what I'd try for a Gaussian with the mean of 0 and standard deviation of 1 from 0 to +infinity:

    from scipy.integrate import quad
    from math import pi, exp
    mean = 0
    sd   = 1
    quad(lambda x: 1 / ( sd * ( 2 * pi ) ** 0.5 ) * exp( x ** 2 / (-2 * sd ** 2) ), 0, inf )
    

    That's a little ugly because the Gaussian function is a little long, but still pretty trivial to write.

提交回复
热议问题