Reputation: 111
Say, I have an equation f(x) = x**2 + 1
, I need to find the value of f(2)
.
Easiest way is to create a function, accept a parameter and return the value.
But the problem is, f(x)
is created dynamically and so, a function cannot be written beforehand to get the value.
I am using cvxpy
for an optimization value. The equation would look something like below:
x = cvx.Variable()
Si = [(cvx.square(prev[i] + cvx.sqrt(200 - cvx.square(x))) for i in range(3)]
prev
is an array of numbers. There will be a Si[0] Si[1] Si[2]
.
How do i find the value of Si[0] for x=20
?
Basically, Is there any way to substitue the said Variable and find the value of equation When using cvxpy ?
Upvotes: 0
Views: 3252
Reputation: 36063
Set the value of the variables and then you can obtain the value of the expression, like so:
>>> x.value = 3
>>> Si[0].value
250.281099844341
(although it won't work for x = 20
because then you'd be taking the square root of a negative number).
Upvotes: 3
Reputation: 18668
In parallel to your cvx versions, you can use lambda to define functions on the fly :
f=[lambda x,i=j : (prev[i] + (200 - x*x)**.5)**2 for j in range(3)] #(*)
Then you can evaluate f[0](20)
, f[1](20)
, and so on.
(*) the i=j
is needed to fit each j
in the associated function.
Upvotes: 0
Reputation: 43527
The general solution to interpreting code on-the-fly in Python is to use the built-in eval() but eval is dangerous with user-supplied input which could do all sorts of nasty to your system.
Fortunately, there are ways to "sandbox" eval using its additional parameters to only give the expression access to known "safe" operations. There is an example of how to limit access of eval
to only white-listed operations and specifically deny it access to the built-ins. A quick look at that implementation looks close to correct, but I won't claim it is foolproof.
The sympy.sympify
I mentioned in my comment uses eval()
inside and carries the same warning.
Upvotes: 0