Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

Let's suppose, I am having the below data:

x = [1, 2.5, 3.4, 5.8, 6]

y = [2, 4, 5.8, 4.3, 4]

I want to create a method that will introduce linearly between 1 and 2.5, 2.5 to 3.4, and so on using Python.

1 Answer

0 votes
by (108k points)
edited by

I think you want to write some interpolation method like y = interpolate(x_values, y_values, x), which will give you the 'y' value at some 'x'? The primary approach is as follows:

  1. First, look out for the indices of the values in x_values which determine an interval comprising of x. For example, for x=3 with your example lists, the containing period would be [x1,x2]=[2.5,3.4], and the indices would be i1=1, i2=2
  2. Then you need to calculate the slope on this interval by (y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1]) (ie dy/dx).
  3. The content at x is now the content at x1 plus the slope multiplied by the distance from x1.
  4. You will additionally need to decide what happens if x is outside the interval of x_values, either it's an error, or you could interpolate "backward", assuming the slope is the same as the first/last interval.

For the best of career growth, check out Intellipaat’s Python Course and get certified! 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...