Search code examples
pythonnumpycvxpy

Python: How do i find an equation's value for a given input


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 ?


Solution

  • 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).