I want to create a program that, given a list of n points, it returns a polynomial to the n-degree. I'm having trouble with 2 things:
1) I can't have a 0 in my points-- this I think I will be able to solve with time.
2) It only works with 2 points. Though I designed it to fit any amount of points, it doesn't work with anything over 2.
My code:
def timesLst(num, lst):
a1 = lst
return ([x*num for x in a1])
def subLsts(L1,L2):
'''returns L1 - L2'''
ans = []
for i in range (0, len(L1)):
ans += [L1[i]-L2[i]]
return (ans)
def zeroRow(clmn, EQs):
'''This function is ment to add a row of 0's to a system of '''\
'''equations, given a list [[coef1, coef2, coef3...value].[coef1...]]'''
newEQs = []
for i in range(0, len(EQs)):
multNum = 1
for j in range (0,i):
multNum *= EQs[j][clmn]
for j in range ((i+1), len(EQs)):
multNum *= EQs[j][clmn]
newEQs += [timesLst(multNum, EQs[i])]
EQs = newEQs
newEQs = [EQs[0]]
for i in range (1, len(EQs)):
newEQs += [subLsts(EQs[0],EQs[i])]
return (newEQs)
def ref(EQs):
copyEQs = EQs
finalMatrix = [EQs[0]]
finalAns = []
for EQ in EQs:
if len(EQ) != (len(EQs)+1):
return ("Error")
else:
for clmn in range (0, len(EQs[0])-2):
EQs = zeroRow(clmn, EQs)[1:]
finalMatrix += [EQs[0]]
rowEchelon = []
for i in range(0, len(copyEQs)):
rowEchelon += [timesLst((1/(finalMatrix[i][i])), finalMatrix[i])]
return (rowEchelon)
def makeString(coefs):
ans = "y = "
for i in range(0,len(coefs)):
x = str(coefs[-i-1])+"*x^"+str(len(coefs)-i-1)+" + "
ans += x
return (ans[:-3])
def findPoly(points):
for point in points:
if points.count(point) != 1 or len(point) != 2:
return (False)
degree = len(points)-1
matrix = []
for i in range(0, len(points)):
matrix += [[]]
for j in range (0, degree+1):
matrix[i] += [(points[i][0])**(degree-j)]
matrix[i] += [points[i][1]]
matrix = ref(matrix)
h = len(matrix)
l = len(matrix[0])
seed = (matrix[-1][-1]/matrix[-1][-2])
coef = [seed]
for i in range(0, h-1):
amt = 0
value = matrix[-i-2][-1]
for j in range(0,l-2):
amt += (matrix[-i-2][-j-2])*coef[j]
coef += [value - amt]
return (makeString(coef))And this is the message I receive when entering "findPoly([(-2,2),(2,-4),(1,-2.5)])":
Traceback (most recent call last):
File "<pyshell#218>", line 1, in <module>
findPoly([(-2,2),(2,-4),(1,-2.5)])
File "C:\Python32\solveSystem.py", line 73, in findPoly
amt += (matrix[-i-2][-j-2])*coef[j]
IndexError: list index out of rangeI greatly appreciate any help. Thanks!
Offline
roijac wrote:
you're trying to access negative indexes (-i-2, -j-2)
![]()
yep, the clue is the bit where it says
IndexError: list index out of range
Offline
I don't think that's the issue because negative indexes work for a 2x2. for the list, list1 = [0,1,2,3]
list1[-1] = 3, list1[-2] = 2 etc.
Offline
bump
Offline