# Cómo resolver una ecuación de 1 parámetro usando 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. 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)
``````

¡Gracias!

preguntado el 12 de febrero de 14 a las 06:02

Sounds like you need a book on numerical methods more than Python programming advice. Here is a tip -- recast the equation to something like `[pdf(x,...)/pdf(x...)] - 1 = 0` and solve that by minimisation or root finding instead. -

I think that if you write down the equation on a piece of paper, you can fairly straightforwardly solve this without numerical methods. -

Sure, but I want to implement it into Python code, since I want to plot those points directly with the accompanied graphs. -

@talonmies Sounds good! So for the minimization would `scipy.optimize.minimize()` be the way to go? EDIT: Just found another one that might be even better suited for this problem: `scipy.optimize.minimize_scalar()` -

You are right, an analytical solution really is more appropriate here. However, I is good to know about these alternatives like minimization for different tasks. I will do both and compare the results. Thanks. -

## 2 Respuestas

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.

Respondido 12 Feb 14, 11:02

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

I plugged in values for `mu` y `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

Respondido 12 Feb 14, 07:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.