Here is the code for interpolation
def lagrange(x):NOTE: Blogger keeps messing up my indentation, I am yet to figure out why.
tmp = scipy.poly1d([0])
result=scipy.poly1d([0])
for i in x.keys():
numerator=scipy.poly1d([1])
denom = 1.0
for j in x.keys():
if (i != j):
tmp = scipy.poly1d([1,-j])
numerator = numerator * tmp
denom = denom * (i - j)
tmp = (numerator/denom) * x.get(i)
result = result + tmp
return result
input = {0:5, 1:10, 2:21}
print lagrange(input)
Sahni's input for the example is {0:1, 1:10, 2:21} and I was surprised to see my program return a different output. Fixing the input, showed the correct results. That reminds me, somebody please ask Sahni to start maintaining useful errata for his books. I searched on the web and found nothing useful.
Running the same algorithm on y = log(x) and input = {1:0, 2:0.3010, 3:0.4771, 4:0.6021}, gave me 00.0123 x^3 - 0.1362 x^2 + 0.6236 x - 0.4997, which corresponds to the cubical approximation of log x (R W Hamming, page 233).
4 comments:
Hi, I just wrote a blog-post about Lagrange polynomials and I hope you don't mind that I modified your code for my use.
Thanks for sharing.
Sorry, I did not post a link to my blog so that you can approve.
http://dafeda.wordpress.com
Hey, Mollier
No issues, please feel free to use it. I looked at your blog entry it is quite cool!
Post a Comment