I am trying to solve some problemas of Calculus using Sympy, but when I do the solve the derivative I cannot work with the results because it is an "Equality" as a condition.
import sympy as sp
x, y, z = sp.symbols('x y z')
sp.init_printing(use_unicode=True)
fx = (0.00282*x**4) + (0.206*x**3) - (4.49*x**2) + (18.8*x) - (93.9)
# Interval
lim_inf = 0
lim_sup = 17
# Derivative
fxl = sp.diff(fx, x)
# Solutions of "derivate(fx) = 0"
sols = sp.solve([x >= lim_inf, x <= lim_sup, fxl], x)
print(sols)
The ouput is:
Eq(x, 2.56905057637722) | Eq(x, 9.67787339919465)
How can I get these two values to continue my implementation? I need to get x=2.569 and x=9.678 to calculate in my function "f(x)".
I tried to do something like:
print(sols[0])
But I got the error:
----> 3 print(sols[0])
4
5
TypeError: 'Or' object is not subscriptable
When you solve inequalities you obtain a logical expression that gives the solution values. The solution could be an equality, a relational, or a more complex logical expression (in your case, an Or
of two relationals). In your particular case where you can see the two equalities and you want to get the numbers you could do the conversion to a set (as suggested above) or simply request the Number
objects from the expression:
>>> from sympy import Number
>>> sols.atoms(Number)
{2.56905057637722, 9.67787339919465}
But this won't always be what you want if there are other types of numbers in the expressions. It is better to make a request with a better defined output (as was suggested above). But, again, rather than using the general "solve" for this specific polynomial, I would suggest using real_roots
which will be fast and as accurate as needed (via evaluation) and filter those solutions. That's more like using the "right tool for the job".
>>> from sympy import real_roots, Interval
>>> [i.n(3) for i in real_roots(fxl) if i in Interval(lim_inf, lim_sup)]
[2.57, 9.68]