Reputation: 275
I used the eval function to evaluate a function. the code is written below:
import numpy as np
import sympy
from sympy import Symbol, Add
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]
a = [1 + 1j, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values
def F(fun, v):
return fun.evalf(subs={s: v}) # Evaluate the function at s=v
f_dis = [F(fun, v) for v in a]
print (f_dis)
fit3 = np.asanyarray(f_dis)
print ("fit3 =", fit3)
realpart = fit3.real[0]
print ("real =", realpart)
the result of f_dis
is
[8.0 + 22.0*I, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]
The point here is that the code shows the 8.0 + 22.0*I
as the real part of the first element, instead of showing 8
only.
What should I do to solve this issue?
Thanks.
Upvotes: 1
Views: 38
Reputation: 39052
You can use re
from Sympy
to get only the real part of the evaluated expression
import numpy as np
from sympy import Symbol, Add, re
s = Symbol('s')
x = [ s, s+1, 10*s**2, 5]
a = [1 + 1j, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values
def F(fun, v):
return fun.evalf(subs={s: v}) # Evaluate the function at s=v
f_dis = [re(F(fun, v)) for v in a] # <---- Use re() here
print (f_dis)
# [8.00000000000000, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]
Upvotes: 1