无法获取从 fun.eval 获得的数组的实部

Having trouble to get the real part of an array obtained from the fun.eval

我使用 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。 我应该怎么做才能解决这个问题? 谢谢。

您可以使用 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]