I'm having some troubles with a homework from my university, so I decided to post here for help
I have to create a list for polynomials. This part is okay:
n = int(input("Degree of polynomial: "))
p = []
for i in range(n+1):
p.append(float(input("p["+str(i)+"]: ")))
i += 1
For example, the polynomial:
5x^4+3x^3-2x^2+x-2
Has:
n = 4
And the list indicated by:
p[] = [5, 3, -2, 1, -2]
Also, I created a list with values that pretend to be roots of a polynomial (listPRoots, the possible roots). This part is also okay:
listPRoots= []
for i in range(int(p[0])):
if p[0]%(i+1) == 0:
listPRoots.append(-(i+1))
listPRoots.append(i+1)
As the code show, I have a list with the values that can be the roots of my polynomial. I used the rational roots theorem to make this list.
Now, I want to take a polynomial with coeficients in a list (p). With this polynomial, I want to verify every value inside the list (called listPRoots) to find the values of the roots of the polynomial. When I find this value, I want to put they in a new list (called listIntegrerRoots). For this, I tried:
listIntegrerRoots = []
listTestRoots = []
for i in range(len(listPRoots) - 1):
flag = len (p) - 1
while flag > 0:
root = (listPRoots[i]**(flag)) * p[flag]
listTestRoots.append(root)
flag = flag- 1
if sum(listTestRoots) + p[0] == 0:
listIntegrerRoots.append(listPRoots[i])
But, I can't get the list I want. For example:
n = 2
p[0] = 6, p[1] = -5, p[2] = 1
result in:
x^2 - 5x + 6
and:
listPRoots[] = [-1, 1, -2, 2, -3, 3, -6, 6]
I would:
listIntegrerRoots[] = [2, 3]
Because 2 and 3 are the roots of my polynomial. But I get:
listIntegrerRoots[] = []
Can someone help me with this?
Thanks.
Just don't froget to clear your sum buffer listTestRoots
every time you test a new possible root value.
Should be something like:
for i in range(len(listPRoots) - 1):
listTestRoots = []
....
And from my point of view, an accumulative sum variable could be a better choice.
-- * Edit * --
In [23]: for i in range(len(listPRoots)):
...: s = 0
...: for j in range(len(p)):
...: s += (listPRoots[i] ** j) * p[j]
...: if s == 0:
...: listIntegerRoots.append(listPRoots[i])
...:
...:
...:
In [24]: listIntegerRoots
Out[24]: [2, 3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.