Python: 我正在尝试使用另一个函数返回的函数
Python: I am trying to use a function returned by another function
我正在学习 Python 科学计算,并且有一个练习,我使用它的根创建多项式:
练习 3.5
from sympy import symbols, expand
def poly(roots): #Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *=(x - r)
return expand(f)
测试:
from numpy.lib.scimath import sqrt
poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
给出:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
我正在尝试 return 多项式并通过传递 x 值来使用它:
f = lambda x: poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
f(-1/2)
给出:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
问题是 f(-1/2) 没有给出它应该给出的 0
。我如何告诉 Python 以代数方式使用表达式?谢谢!
您必须替换 x
并将多项式计算为浮点数:
poly(...).subs('x', y).evalf()
尝试一下:
from sympy import symbols, expand, sqrt
def poly(roots): # Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *= (x - r)
return expand(f)
f = lambda y: poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73), (-7 / 2) - (1 / 2) * sqrt(73)]).subs('x',
y).evalf()
print(f(-1 / 2))
输出:
-1.06581410364015e-14
您还可以使用 python 的内置 eval() 和 str() 函数。 eval() 将字符串作为输入。
from sympy import symbols, expand,sqrt
def poly(roots): #Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *=(x - r)
return str(expand(f))
f = lambda x: eval(poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73),(-7 / 2) - (1 / 2) * sqrt(73)]))
print(f(-1/2))
输出:
0.0
我正在学习 Python 科学计算,并且有一个练习,我使用它的根创建多项式:
练习 3.5
from sympy import symbols, expand
def poly(roots): #Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *=(x - r)
return expand(f)
测试:
from numpy.lib.scimath import sqrt
poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
给出:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
我正在尝试 return 多项式并通过传递 x 值来使用它:
f = lambda x: poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
f(-1/2)
给出:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
问题是 f(-1/2) 没有给出它应该给出的 0
。我如何告诉 Python 以代数方式使用表达式?谢谢!
您必须替换 x
并将多项式计算为浮点数:
poly(...).subs('x', y).evalf()
尝试一下:
from sympy import symbols, expand, sqrt
def poly(roots): # Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *= (x - r)
return expand(f)
f = lambda y: poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73), (-7 / 2) - (1 / 2) * sqrt(73)]).subs('x',
y).evalf()
print(f(-1 / 2))
输出:
-1.06581410364015e-14
您还可以使用 python 的内置 eval() 和 str() 函数。 eval() 将字符串作为输入。
from sympy import symbols, expand,sqrt
def poly(roots): #Pass real and/or complex roots
x = symbols('x')
f = 1
for r in roots:
f *=(x - r)
return str(expand(f))
f = lambda x: eval(poly([-1 / 2, 5, (21 / 5), (-7 / 2) + (1 / 2) * sqrt(73),(-7 / 2) - (1 / 2) * sqrt(73)]))
print(f(-1/2))
输出:
0.0