Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

python - Interpolate between linear and nonlinear values

I have been able to interpolate values successfully from linear values of x to sine-like values of y.
However - I am struggling to interpolate the other way - from nonlinear values of y to linear values of x.

The below is a toy example

import matplotlib.pylab as plt
from scipy import interpolate
#create 100 x values
x = np.linspace(-np.pi, np.pi, 100)
#create 100 values of y where y= sin(x)
y=np.sin(x)
#learn function to map y from x
f = interpolate.interp1d(x, y)

With new values of linear x

xnew = np.array([-1,1])

I get correctly interpolated values of nonlinear y

ynew = f(xnew)
print(ynew)    
array([-0.84114583,  0.84114583])

The problem comes when I try and interpolate values of x from y.

I create a new function, the reverse of f:

f2 = interpolate.interp1d(y,x,kind='cubic')

I put in values of y that I successfully interpolated before

ynew=np.array([-0.84114583, 0.84114583])

I am expecting to get the original values of x [-1, 1]

But I get:

array([-1.57328791,  1.57328791])

I have tried putting in other values for the 'kind' parameter with no luck and am not sure if I have got the wrong approach here. Thanks for your help

question from:https://stackoverflow.com/questions/65934478/interpolate-between-linear-and-nonlinear-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess the problem raises from the fact, that x is not a function of y, since for an arbitrary y value there may be more than one x value found.

Take a look at a truncated range of data. When x ranges from 0 to np.pi/2, then for every y value there is a unique x value. In this case the snippet below works as expected.

>>> import numpy as np
>>> from scipy import interpolate
>>> x = np.linspace(0, np.pi / 2, 100)
>>> y = np.sin(x)
>>> f = interpolate.interp1d(x, y)
>>> f([0, 0.1, 0.3, 0.5])
array([0.        , 0.09983071, 0.29551713, 0.47941047])
>>> f2 = interpolate.interp1d(y, x)
>>> f2([0, 0.09983071, 0.29551713, 0.47941047])
array([0.        , 0.1       , 0.3       , 0.50000001])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...