Reputation: 8260
After a working with SyMpy library I receive an expression (in yprime variable).
from sympy import *
x = Symbol('x')
y = 1 - (0.1 * coeff1) / (x + 2) - sin(x) * (2 * x + coeff1)
yprime = y.diff(x)
Then I try to use yprime in calculations, but Python interpret it as a text: -(2*x + 1.0)*cos(x) - 2*sin(x) + 0.1/(x + 2)**2
How may I calculate -(2*x + 1.0)*cos(x) - 2*sin(x) + 0.1/(x + 2)**2 ?
After some manipulations according to mtadd:
from sympy import *
x, coeff1 = symbols('x coeff1')
y = 1 - (0.1 * coeff1) / (x + 2) - sin(x) * (2 * x + coeff1)
yprime = y.diff(x).evalf(subs={x:0,coeff1:1})
I receive a digital result, but still it's unable to operate with further logic. It says:
TypeError: can't convert expression to float
Upvotes: 1
Views: 594
Reputation: 2555
Call the method subs
on your symbolic expression to calculate an analytic expression. You can call evalf
on the analytic expression to a numeric solution in a Python float. Below is some example output from isympy after entering your input from above (coeff1 = 1.0).
In [18]: yprime
Out[18]:
0.1
-(2⋅x + 1.0)⋅cos(x) - 2⋅sin(x) + ────────
2
(x + 2)
In [19]: yprime.subs(x,2*pi)
Out[19]:
0.1
-4⋅π - 1.0 + ──────────
2
(2 + 2⋅π)
In [20]: yprime.subs(x,2*pi).evalf()
Out[20]: -13.5649131254944
The following program:
from sympy import *
x, C1 = symbols('x C1')
y = 1-(0.1*C1)/(x+2)-sin(x)*(2*x+C1)
print y.diff(x).evalf(subs={x:pi/2,C1:1})
prints -1.99215722345589 with sympy version 0.7.2 and python 2.7.3.
Upvotes: 2
Reputation: 409
I think this might help Evaluating a mathematical expression in a string I think yprime is being interpreted as a string and this first answer of the post describes how to evaluate a string as an arithmetic expression.
Upvotes: 0