Reputation: 10751
Suppose I have a Python function y
of x
, where x
must be a number, and the return value is always a number. y
is a mathematical function of one variable.
Is there a function in Python (i.e., in numpy
, scipy
, etc.) that would be able to solve for the particular value(s) for x
that produces a desired return value -- using, e.g., gradient descent?
I'm looking for a magic_function
that would do something like this:
>>> from my_module import y
>>> from magic_package import magic_function
>>> desired = 10
>>> x = magic_function(y, desired)
>>> y(x)
10
Upvotes: 0
Views: 336
Reputation: 55469
You can wrap your function y(x) so that it's offset by the desired value. Here's a simple demo of the long way to do that:
def y(x):
return x*x
def offset_function(f, desired=0):
def newf(x):
return f(x) - desired
return newf
y9 = offset_function(y, 9)
for x in range(5):
print x, y(x), y9(x)
output
0 0 -9
1 1 -8
2 4 -5
3 9 0
4 16 7
However, it's simpler just to use a lambda
:
y9 = lambda x: y(x) - 9
You can pass that to your root-finder like this:
scipy.optimize.root(lambda x: y(x) - 9, xguess)
Upvotes: 2