Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python
# shitty way of doing a Lagrange interpolation
def lagint(xarr,yarr):
p = []
k = len(xarr) # rank+1
for i in range(k):
Li = []
for j in range(k):
if (j != i):
Lij = {
"xj" : str(xarr[j]),
"div" : xarr[i] - xarr[j]
}
Li.append(Lij)
pi = {
'yi' : yarr[i],
'Li' : Li
}
p.append(pi)
return p
def pprintli(lagint):
# pretty print of given p(x)
# found via previous lagint func
p = ''
for pi in lagint:
yid = pi['yi']
for Lij in pi['Li']:
yid /= Lij['div']
if yid>0:
p += '\n + '
else:
yid = abs(yid)
p += '\n - '
p += '%.4f'%(yid)+'*'
p += ''.join('(x-'+Lij['xj']+')' for Lij in pi['Li'])
print(' '+p[3:])
# xarr = [x1,x2,...,xn]
# yarr = [y1,y1,...,yn]
# pprint(lagint(xarr,yarr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.