Alpha_Lupi
Alpha_Lupi

Reputation: 21

How do you find the inverse of a function?

There are also other variables, such as c1, n1, k1 and so on but they are only being used as placeholders for a random number from 1 to 10. Specifically, I am trying to find the maximum y-value of a function, calculate %90 of that value, and then plug that back in to the inverse of the function in order to find the x-value at 90% of maximum y-value. I am able to calculate the rest of these except I have to manually find the inverse of a function which is going to be an issue when I eventually have to find this x-value at 90% of input for any function. Also I am going to be mainly using sigmoidal functions.

This is one of the functions that I want to find the inverse for:

def c(x):
    return ((c1*x**(n2*n1))*(c2**n1))/((k2*(k2+(x**n2))**n1)+((c2**n1)*(x**(n2*n1))))

Key issue: I need to use python to find the inverse of a function.

Upvotes: 2

Views: 2631

Answers (1)

J. Choi
J. Choi

Reputation: 1835

You can use root-finding methods to numerically find the inverse of a function.

However, you should carefully check the shape of the function.

  • There can be multiple x values that result in a same f(x) value.
  • Numerical methods can fail to find a root if the shape of the function is complicated.

For example, your function generates similar values in many cases:

def f(x, c1, c2, n1, n2, k2):
    return ((c1*x**(n2*n1))*(c2**n1))/((k2*(k2+(x**n2))**n1)+((c2**n1)*(x**(n2*n1))))

f(10000.0, 2, 3, 4, 5, 6)
> 1.8620689655172415

f(1000.0, 2, 3, 4, 5, 6)
> 1.8620689655172382

f(10.0, 2, 3, 4, 5, 6)
> 1.8620381428016617

f(8.0, 2, 3, 4, 5, 6)
> 1.861974887879328

You will not get an exact inverse value for this function:

def f_inv_opt(x, y, c1, c2, n1, n2, k2):
    return abs(f(x, c1, c2, n1, n2, k2) - y)

scipy.optimize.minimize(f_inv_opt, x0 = 2.0, args = (f(1000.0, 2, 3, 4, 5, 6), 2, 3, 4, 5, 6))
> 10.99236547

scipy.optimize.minimize(f_inv_opt, x0 = 100.0, args = (f(1000.0, 2, 3, 4, 5, 6), 2, 3, 4, 5, 6))
> 100.0

scipy.optimize.minimize(f_inv_opt, x0 = 1000.0, args = (f(1000.0, 2, 3, 4, 5, 6), 2, 3, 4, 5, 6))
> 1000.0

Note. SymPy cannot analytically solve your complicated equation.

Moreover, I am not sure about the existence of the analytical inverse.

import sympy

x = sympy.symbols('x')
y = sympy.symbols('y')
c1 = sympy.symbols('C_1')
c2 = sympy.symbols('C_2')
n1 = sympy.symbols('n_1')
n2 = sympy.symbols('n_2')
k2 = sympy.symbols('k_2')

expr = ((c1*x**(n2*n1))*(c2**n1))/((k2*(k2+(x**n2))**n1)+((c2**n1)*(x**(n2*n1))))

eqn = sympy.Eq(y, expr)
inv = sympy.solve(eqn, x)
> NotImplementedError

Upvotes: 4

Related Questions