Python - polynomial solution for y

I take a function (e.g. y = x ** 2) and it needs to be solved for x. I know I can solve this problem manually, but I'm trying to find a method instead. I looked through layered, lean and pretty, but didn't seem to find what I was looking for. I am currently making a lambda from a function, so it would be nice if I could save this format for this method, but not necessarily.

Thanks!

+4
source share
3 answers

If you are looking for numerical solutions (that is, you are only interested in numbers, not closed-loop symbolic solutions), then for you in SciPy.optimize . For something simple, newton is a pretty good start for simple polynomials, but you can take it from there.

For symbolic solutions (i.e. to get y = x ** 2 โ†’ x = +/- sqrt (y)), SymPy solver gives you something you need. The entire SymPy package is aimed at performing symbolic manipulations.

Here is an example of using the Python interpreter to solve the equation mentioned in the question. You will need to make sure that the Sympy package is installed, and then:

 >>>> from sympy import * # we are importing everything for ease of use >>>> x = Symbol("x") >>>> y = Symbol("y") # create the two variables >>>> equation = Eq(x ** 2, y) # create the equation >>>> solve(equation, x) [y**(1/2), -y**(1/2)] 

As you understand, the basics are based on real work, even as an interactive algebra system. Not as good as Mathematica , but again, it's free, and you can include it in your own programs. Be sure to read the Gotchas and Pitfalls section of the SymPy documentation on how to code the corresponding equations.

If all this was to get quick and dirty solutions to equations, then there is always Wolfram Alpha .

+10
source

Use Newton-Raphson via scipy.optimize.newton . He finds the roots of the equation, i.e. The values โ€‹โ€‹of x for which f (x) = 0. In the example, you can set the problem as finding the root of the function f (x) = x & sup2; - y. If you supply a lambda that computes y, you can provide a general solution this way:

 def inverse(f, f_prime=None): def solve(y): return newton(lambda x: f(x) - y, 1, f_prime, (), 1E-10, 1E6) return solve 

Using this function is pretty simple:

 >>> sqrt = inverse(lambda x: x**2) >>> sqrt(2) 1.4142135623730951 >>> import math >>> math.sqrt(2) 1.4142135623730951 

Depending on the input function, you may need to set the parameters to newton() . The current version uses initial assumption 1, a tolerance of 10 -10, and a maximum number of iterations of 10 6 .

For additional acceleration, you can provide a derivative of the function in question:

 >>> sqrt = inverse(lambda x: x**2, lambda x: 2*x) 

In fact, without it, the function actually uses the secant method instead of Newton-Raphson, which relies on knowledge of the derivative.

+3
source

Check SymPy, in particular solver .

+3
source

All Articles