[英]Python: I am trying to use a function returned by another function
I am learning Python for scientific computing, and there is an exercise where I create a polynomial using its roots: 我正在学习用于科学计算的Python,在一个练习中,我使用其根创建多项式:
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)
Test: 测试:
from numpy.lib.scimath import sqrt
poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
Gives: 给出:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
I am trying to return the polynomial and use it by passing ax value: 我试图返回多项式并通过传递ax值来使用它:
f = lambda x: poly([-1/2, 5,(21/5),(-7/2) + (1/2)*sqrt(73), (-7/2) - (1/2)*sqrt(73)])
f(-1/2)
Gives: 给出:
x**5 - 1.7*x**4 - 50.5*x**3 + 177.5*x**2 - 24.8999999999999*x - 63.0
The problem is that f(-1/2) is not giving 0
, which it should. 问题是f(-1/2)没有给出0
,它应该给出。 How can I tell Python to use the expression algebraically? 如何告诉Python以代数方式使用该表达式? Thank you! 谢谢!
You have to substitute for x
and evaluate the polynomial to a float: 您必须替换x
并将多项式评估为浮点数:
poly(...).subs('x', y).evalf()
Try with it: 试试看:
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))
Output: 输出:
-1.06581410364015e-14
You can also use python's builtin eval() and str() function. 您还可以使用python的内置eval()和str()函数。 eval() takes a string as an input. 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))
Output: 0.0
输出: 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.