How to solve an 1-parameter equation using Python (scipy/numpy?)

烈酒焚心 提交于 2020-01-07 03:40:13

问题


I hope you have some useful tip for me to approach the following task:

I wrote some simple python snippet to plot probability density functions. In my particular case, let them represent class-conditional probabilities for some parameter x.

So, I am wondering if there is an clever approach (i.e., module) in Python (maybe via a NumPy or SciPy function or method) to solve a simple equation for parameter x. E.g.,

pdf(x, mu=10, sigma=3**0.5) / pdf(x, mu=20, sigma=2**0.5) = 1
# get x

Right now, I can only thing of an brute force approach where I use something like x = np.arange(0, 50, 0.000001) and keep the x value in the vector that yields the closest value for 1 when calculating the ratio pdf1/pdf2.

Below is the code I wrote to calculate the pdf and plot the ratio:

def pdf(x, mu=0, sigma=1):
    """Calculates the normal distribution's probability density 
        function (PDF).  

    """
    term1 = 1.0 / ( math.sqrt(2*np.pi) * sigma )
    term2 = np.exp( -0.5 * ( (x-mu)/sigma )**2 )
    return term1 * term2


x = np.arange(0, 100, 0.05)

pdf1 = pdf(x, mu=10, sigma=3**0.5)
pdf2 = pdf(x, mu=20, sigma=2**0.5)

# ...
# ratio = pdf1 / pdf2
# plt.plot(x, ratio)

Thanks!


回答1:


In general, it sounds like you need the scalar root-finding functions: http://docs.scipy.org/doc/scipy/reference/optimize.html

But as others have pointed out, it seems like there is an analytical solution.




回答2:


Since you have a nice closed-form equation, you can solve it with SymPy.

I plugged in values for mu and sigma and entered this into Sympy Gamma:

 solve(1.0 / ( sqrt(2*pi) *(3**0.5) ) * exp( -0.5 * ( (x-10)/(3**0.5) )**2 ) /  (1.0 / ( sqrt(2*pi) *(2**0.5) ) * exp( -0.5 * ( (x-20)/(2**0.5) )**2 ))-1,x)

The result: 15.4554936768195



来源:https://stackoverflow.com/questions/21720489/how-to-solve-an-1-parameter-equation-using-python-scipy-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!