-2

I started learning Python and I have been referring to "A primer on Scientific Programming with Python by HP Langtangen". I just started the topic on functions and I have been assigned a task to develop a function which computes a polynomial by product. The exact question being

Given n+1 roots r0, r1, . . . , rn of a polynomial p(x) of degree n+1, p(x) can be computed by

p(x) = (x - r0)(x - r1) · · · (x - rn-1)(x - rn)

Write a function poly(x, roots) that takes x and a list roots of the roots as arguments and returns p(x)

Is there any way this problem can be solved without using Sympy?

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
abe25
  • 27
  • 4

1 Answers1

0

You just need to iterate.

def poly(x, roots):
    poly = 1
    for r in roots:
        poly *= (x - r)

    return poly

# EXAMPLE
x = 1
roots = [2, 5, 7]
print ( poly(x, roots) ) 
Juan Leni
  • 6,982
  • 5
  • 55
  • 87
  • Thank you mtk99 for your input. But it would evaluate the function at x = 1. The desired output is the polynomial equation, which according to input has to be (x-2)(x-5)(x-7). – abe25 Feb 27 '16 at 08:50
  • The last line was just and example! What you are asking was just the function poly(x, roots) – Juan Leni Feb 27 '16 at 08:52
  • Oh yeah. I do understand that the last line was an example. But when I run the function as poly(x,[2,5,7]), it gives me TypeError: unsupported operand type(s) for -: 'function' and 'int' – abe25 Feb 27 '16 at 08:56
  • You must be doing something wrong.. Could you post your code? – Juan Leni Feb 27 '16 at 09:00
  • roots = [-1,1,2] def poly(roots,x): p = 1 for i in range(len(roots)): p = p*(x - roots[i]) return p print(poly(roots,3)) – abe25 Feb 27 '16 at 09:03
  • Sorry, but that works on my side with no error. There is still a logic problem. Keep in mind that if there are no roots, you probably want to return 0 but your code returns 1 – Juan Leni Feb 27 '16 at 09:06
  • thanks @mtk99. I will check my code logic once again to see where I am going wrong Thanks for all the help – abe25 Feb 27 '16 at 09:07
  • If there are no roots, returning the constant function 1 is rather logical. Returning the constant 0 gives a function with infinitely many zeros, for an input that prescribes no roots at all. – Lutz Lehmann Mar 04 '16 at 14:13