[英]How to solve an 1-parameter equation using Python (scipy/numpy?)
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. 我写了一些简单的python代码段来绘制概率密度函数。 In my particular case, let them represent class-conditional probabilities for some parameter x
. 在我的特定情况下,让它们表示某些参数x
类条件概率。
So, I am wondering if there is an clever approach (ie, module) in Python (maybe via a NumPy or SciPy function or method) to solve a simple equation for parameter x
. 因此,我想知道Python中是否有一个聪明的方法(例如,模块)(也许通过NumPy或SciPy函数或方法)来解决参数x
的简单方程式。 Eg, 例如,
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.
现在,我只能采用蛮力方法,例如使用x = np.arange(0, 50, 0.000001)
并在计算比率pdf1/pdf2.
时将x值保留在矢量中,该矢量会产生最接近1的值。 pdf1/pdf2.
Below is the code I wrote to calculate the pdf and plot the ratio: 下面是我编写的用于计算pdf并绘制比率的代码:
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! 谢谢!
Since you have a nice closed-form equation, you can solve it with SymPy. 由于您有一个很好的封闭形式方程式,因此可以使用SymPy求解。
I plugged in values for mu
and sigma
and entered this into Sympy Gamma : 我插入了mu
和sigma
值,并将其输入到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 结果:15.4554936768195
In general, it sounds like you need the scalar root-finding functions: http://docs.scipy.org/doc/scipy/reference/optimize.html 通常,听起来您需要标量根查找功能: http : //docs.scipy.org/doc/scipy/reference/optimize.html
But as others have pointed out, it seems like there is an analytical solution. 但是,正如其他人指出的那样,似乎存在一种分析解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.