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.
source share