我使用eval函数评估函数。代码写在下面:
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)
f_dis
的结果是
[8.0 + 22.0*I, 50.0000000000000, 102.000000000000, 174.000000000000, 266.000000000000]
这里的要点是代码将8.0 + 22.0*I
显示为第一个元素的真实部分,而不是仅显示8
。
我应该怎么做才能解决这个问题?
谢谢。
答案 0 :(得分:1)
您可以使用Sympy
中的re
来仅获取评估表达式的实部
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]