Johnathan - 1 year ago 66

Python Question

I am learning Python for scientific computing, and there is an exercise where I create a polynomial using its roots:

`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`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**