There is a variable interpolation function in Java:

public static double Interpolation(double m) { int k = 0; double x[] = {2000, 2500, 3000, 4000, 5000}; double y[] = {0.032, 0.034, 0.040, 0.040, 0.038}; for (int i = 1; i < 5; i++) if (m <= x[i] && m >= x[i - 1]) { k = i; } double a = (y[k] - y[k - 1]) / (x[k] - x[k - 1]); double b = y[k - 1] - a * x[k - 1]; return (a * m + b); 

Interested in how it will look

  if (m <= x[i] && m >= x[i - 1]) { k = i; } double a = (y[k] - y[k - 1]) / (x[k] - x[k - 1]); double b = y[k - 1] - a * x[k - 1]; 

in python.

  • Do you want to transfer this particular function to Python or are you ready to use ready-made and fast features in Python? Those. Do you have an academic or practical task? - MaxU
  • The task is practical, you can use ready-made functions, the approach in Python language is interesting. - Aleksandr Aleksandrov

2 answers 2

I would use SciPy :

 import numpy as np from scipy import interpolate import matplotlib.pyplot as plt # Original points x = np.array([2000, 2500, 3000, 4000, 5000], dtype=np.float64) y = np.array([0.032, 0.034, 0.040, 0.040, 0.038], dtype=np.float64) # Points to interpolate X = np.linspace(x.min(), x.max(), 21) # different interpolation methods (functions) f_linear = interpolate.interp1d(x, y, kind='linear') f_nearest = interpolate.interp1d(x, y, kind='nearest') f_zero = interpolate.interp1d(x, y, kind='zero') f_slinear = interpolate.interp1d(x, y, kind='slinear') # spline interp. of 1st order f_quadratic = interpolate.interp1d(x, y, kind='quadratic') # spline interp. of 2nd order f_cubic = interpolate.interp1d(x, y, kind='cubic') # spline interp. of 3rd order # plot plt.style.use('ggplot') plt.figure(figsize=(20, 14)) # plot interpolated points plt.plot(X, f_linear(X), '-o', X, f_nearest(X), '-^', #X, f_zero(X), '-*', X, f_slinear(X), '-*', X, f_quadratic(X), '-D', X, f_cubic(X), '-H', linewidth=1.5) # plot original points plt.scatter(x, y, marker='o', s=500, c='green') plt.legend(['Linear', 'Nearest', 'Linear Spline', 'Quadratic Spline', 'Cubic Spline', 'Original points']) plt.xlim(x.min() * 0.95, x.max() * 1.05) plt.show() 

enter image description here

    If you just translate your code, it will turn out like this:

     def Interpolation(m): x = [2000, 2500, 3000, 4000, 5000] y = [0.032, 0.034, 0.040, 0.040, 0.038] for i in range(1, len(x)): if x[i - 1] <= m <= x[i]: k = i a = float(y[k] - y[k - 1]) / (x[k] - x[k - 1]) b = y[k - 1] - a * x[k - 1] return a * m + b 

    This code will work in both Python 2 and Python 3 , although casting to float in version 3 is not necessary.

    Here optimization is also possible, significantly accelerating the code for the case of large sizes of arrays x and y - binary search. Also, I would add checks for m , in case it falls outside the range of x , otherwise the code will fall.