Python:我试图使用另一个函数返回的函数

时间:2016-11-19 02:37:00

标签: python python-3.x sympy polynomials

我正在学习用于科学计算的Python,并且有一个练习,我用它的根创建一个多项式:

enter image description here

练习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

我试图返回多项式并通过传递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,它应该是。{1}。如何告诉Python以代数方式使用表达式?谢谢!

2 个答案:

答案 0 :(得分:1)

您必须替换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

答案 1 :(得分:1)

您还可以使用python的builtin eval()和str()函数。 eval()接受一个字符串作为输入。

    variable succes_Counter
variable unsuccess_Counter = 0
boolean color_not found = true
for i in range(len(colours)):
    {

            if colours[i] == voiceRecog
            {
                print("color found + colours[i] + ")
                succes_Counter += 1

                //HERE IT EXISTS FROM THIS LOOP

                break
            }
            elseif voiceRecog == "quit"

            //HERE IT EXISTS FROM THIS LOOP
                break


            else
                if color_not found == true
                {
                print(" color not found")

                unsuccess_Counter +=1

                color_not found = false
                }
        }


            color_not found = true
            print("\nYou checked for", unsuccess_Counter, "colours and had", succes_Counter, "successful attempts")

输出:     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))