Johnathan Johnathan - 18 days ago 5
Python Question

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:

enter image description here

Exercise 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)


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 a x value:

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. How can I tell Python to use the expression algebraically? Thank you!

Answer

You have to substitute for x and evaluate the polynomial to a float:

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