简体   繁体   中英

lagrange interpolation Python

I am trying to use scipy.interpolate.lagrange to interpolate the following data, which is of degree 8:

x_data = [1900., 1910., 1920., 1930., 1940., 1950., 1960., 1970., 1980.]

y_data = [76212168., 92228496., 106021537., 123202624., 132164569., 151325798., 179323175., 203302031., 226542199.]

with python code: poly = scipy.interpolate.lagrange(x_data, y_data)

But the output looks not correct because even none of the (x_data[i], y_data[i]) pairs lies on the 'poly' I got from the scipy.interpolate.lagrange call.

Could anybody give any hints or suggestion? Thanks so much.

Your values are poorly scaled, and, as the lagrange docstring says, "Warning: This implementation is numerically unstable." Try applying lagrange to, say, the "whitened" data (ie shift and scale the data to have mean 0 and standard deviation 1). For example,

xm = np.mean(x_data)
xscale = np.std(x_data)
ym = np.mean(y_data)
yscale = np.std(y_data)
x = (x_data - xm) / xscale
y = (y_data - ym) / yscale
poly = scipy.interpolate.lagrange(x, y)

( np comes from import numpy as np .)

Then to use poly on "raw" (ie unscaled) data, use the same transform on the x input when you call poly , and undo the y transform on the values returned by poly . Eg if xx is an array with values in the interval [1900, 1980]:

yy = poly((xx - xm)/xscale)*yscale + ym

Before you spend too much time on this, though, I have to ask: Why are you using Lagrange interpolation? It is an important theoretical tool, but it is not so good for practical data analysis (see http://en.wikipedia.org/wiki/Lagrange_polynomial#Notes ; in particular, note the occurrence of Runge's phenomenon). Why do you need to interpolate at all? What are you going to do with the interpolator? If you have answers to those questions, you should include them as part of the question.

Here create its own function a lagrange interpolation. Maybe you're using her

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM