Tharif
Tharif

Reputation: 13971

Finding roots of a polynomial using numpy

Following code will find roots of a polynomial:

import numpy as np
print("Roots of the first polynomial:")
print(np.roots([1, -2, 1]))

But i cannot get output for roots if use:

import numpy as np
print("Roots of the first polynomial:")
print(roots([1, -2, 1]))

I assume since roots is a sub module, we need to access roots using alias of numpy ie np; I could not find in detail about roots, please share your thoughts on the same.

Upvotes: 1

Views: 547

Answers (1)

cs95
cs95

Reputation: 402333

roots is a function, not a submodule. When you call np.roots, you're accessing the function through the numpy module's namespace. Run help(np.roots) if you want to see more.

roots(p)
Return the roots of a polynomial with coefficients given in p.

If you want to bring roots into your own namespace, you use the from .. import .. syntax:

import numpy as np
from numpy import roots

Which imports numpy and brings the roots function into your own namespace so you can call it as you were doing so in the second snippet.

Upvotes: 1

Related Questions