SoFunction
Updated on 2025-03-07

C# linear interpolation implementation example

Linear interpolation is a commonly used interpolation algorithm that is suitable for many practical scenarios.

  • Sensor data processing: In sensor data processing, data points may be discontinuous or uneven. Using linear interpolation allows you to estimate the numerical values ​​between two data points based on known data points, thereby filling in the missing or discontinuities in the data.

  • Image processing: In image processing, it may be necessary to adjust the size or resolution of the image. Linear interpolation can be used to estimate the numerical value of new pixel points, thereby achieving image scaling or enlarging.

  • Signal processing: In digital signal processing, linear interpolation can be used to estimate the numerical value of the signal between discrete time points, thereby smoothing out the signal or filling the missing value in the signal.

  • Numerical simulation: In linear numerical simulation, linear interpolation can be used to approximate the numerical output of complex functions, thereby simplifying the calculation process of mathematical models.

  • Kinematic Model: In a linear kinematic model, it may be necessary to estimate the trajectory or position information of an object at different time points based on known position data, and linear interpolation can help achieve this goal.

CaseThere is a set of data, voltage and temperature will change with each other. The voltage and temperature are floating point data, and the voltage corresponding to the shaping temperature is quickly obtained (-40~120).

using System;

class Program
{
    static void Main()
    {
        // Assume a known voltage-temperature data point        double[] temperatures = { -40, 0, 25, 50, 100 };
        double[] voltages = { 1.0, 2.5, 3.0, 3.5, 4.0 };

        // Integer temperature value to be obtained        int targetTemperature = 75;

        // Find adjacent temperature data points        int lowerIndex = (temperatures, targetTemperature);
        if (lowerIndex < 0)
        {
            lowerIndex = ~lowerIndex - 1;
        }
        int upperIndex = lowerIndex + 1;

        // Linear interpolation to calculate voltage value        double lowerTemperature = temperatures[lowerIndex];
        double upperTemperature = temperatures[upperIndex];
        double lowerVoltage = voltages[lowerIndex];
        double upperVoltage = voltages[upperIndex];

        double interpolatedVoltage = lowerVoltage + (upperVoltage - lowerVoltage) * (targetTemperature - lowerTemperature) / (upperTemperature - lowerTemperature);

        ($"At temperature {targetTemperature} The corresponding voltage value is: {interpolatedVoltage}");
    }
}

1. Segmented linear interpolation

        /// <summary>  
        /// Segmented linear interpolation, interpolation of a set of numbers into the required number of points        /// </summary>  
        /// <param name="dataIn">Array of data to be interpolated</param>        /// <param name="n">Interpolated points</param>        /// <returns>Interpolated data array</returns>        public static float[] Interpolation(float[] dataIn, int n)
        {
            float[] dataOut = new float[n];
            int lenIn = ;
            float[] a = new float[lenIn];
            float[] divIn = new float[lenIn];
            float[] divOut = new float[n];

            divIn[0] = 0;

            for (int i = 1; i &lt; lenIn; i++)
            {
                divIn[i] = divIn[i - 1] + 1;
            }

            divOut[0] = 0;

            for (int i = 1; i &lt; n; i++)
            {
                divOut[i] = divOut[i - 1] + lenIn / (float)n;
            }
            int k = 0;
            for (int i = k; i &lt; n; i++)
            {
                for (int j = 0; j &lt; lenIn - 1; j++)
                {
                    if (divOut[i] &gt;= divIn[j] &amp;&amp; divOut[i] &lt; divIn[j + 1])
                    {
                        dataOut[i] = (dataIn[j + 1] - dataIn[j]) * (divOut[i] - divIn[j]) / (divIn[j + 1] - divIn[j]) + dataIn[j];
                        k = i;
                    }
                }
            }

            return dataOut;
        }

2. Cubic spline interpolation

        /// &lt;summary&gt;
        /// Cubic spline interpolation        /// &lt;/summary&gt;
        /// <param name="points">Sorted x and y points set</param>        /// <param name="xs">Input x-axis data, interpolate to calculate the corresponding y-axis point</param>        /// <param name="chf">Write 1</param>        /// <returns>Returns the calculated Y-axis value</returns>        public static double[] SplineInsertPoint(PointClass[] points, double[] xs, int chf)
        {
            int plength = ;
            double[] h = new double[plength];
            double[] f = new double[plength];
            double[] l = new double[plength];
            double[] v = new double[plength];
            double[] g = new double[plength];

            for (int i = 0; i &lt; plength - 1; i++)
            {
                h[i] = points[i + 1].x - points[i].x;
                f[i] = (points[i + 1].y - points[i].y) / h[i];
            }

            for (int i = 1; i &lt; plength - 1; i++)
            {
                l[i] = h[i] / (h[i - 1] + h[i]);
                v[i] = h[i - 1] / (h[i - 1] + h[i]);
                g[i] = 3 * (l[i] * f[i - 1] + v[i] * f[i]);
            }

            double[] b = new double[plength];
            double[] tem = new double[plength];
            double[] m = new double[plength];
            double f0 = (points[0].y - points[1].y) / (points[0].x - points[1].x);
            double fn = (points[plength - 1].y - points[plength - 2].y) / (points[plength - 1].x - points[plength - 2].x);

            b[1] = v[1] / 2;
            for (int i = 2; i &lt; plength - 2; i++)
            {
                // (" " + i);
                b[i] = v[i] / (2 - b[i - 1] * l[i]);
            }
            tem[1] = g[1] / 2;
            for (int i = 2; i &lt; plength - 1; i++)
            {
                //(" " + i);
                tem[i] = (g[i] - l[i] * tem[i - 1]) / (2 - l[i] * b[i - 1]);
            }
            m[plength - 2] = tem[plength - 2];
            for (int i = plength - 3; i &gt; 0; i--)
            {
                //(" " + i);
                m[i] = tem[i] - b[i] * m[i + 1];
            }
            m[0] = 3 * f[0] / 2.0;
            m[plength - 1] = fn;
            int xlength = ;
            double[] insertRes = new double[xlength];
            for (int i = 0; i &lt; xlength; i++)
            {
                int j = 0;
                for (j = 0; j &lt; plength; j++)
                {
                    if (xs[i] &lt; points[j].x)
                        break;
                }
                j = j - 1;
                (j);
                if (j == -1 || j ==  - 1)
                {
                    if (j == -1)
                        throw new Exception("The boundary below interpolation exceeds");
                    if (j ==  - 1 &amp;&amp; xs[i] == points[j].x)
                        insertRes[i] = points[j].y;
                    else
                        throw new Exception("The boundary below interpolation exceeds");
                }
                else
                {
                    double p1;
                    p1 = (xs[i] - points[j + 1].x) / (points[j].x - points[j + 1].x);
                    p1 = p1 * p1;
                    double p2; p2 = (xs[i] - points[j].x) / (points[j + 1].x - points[j].x);
                    p2 = p2 * p2;
                    double p3; p3 = p1 * (1 + 2 * (xs[i] - points[j].x) / (points[j + 1].x - points[j].x)) * points[j].y + p2 * (1 + 2 * (xs[i] - points[j + 1].x) / (points[j].x - points[j + 1].x)) * points[j + 1].y;

                    double p4; p4 = p1 * (xs[i] - points[j].x) * m[j] + p2 * (xs[i] - points[j + 1].x) * m[j + 1];
                    //         (m[j] + " " + m[j + 1] + " " + j);
                    p4 = p4 + p3;
                    insertRes[i] = p4;
                    //("f(" + xs[i] + ")= " + p4);
                }

            }
            //();
            return insertRes;
        }

Sort calculation

     public class PointClass
    {
        public double x = 0;
        public double y = 0;
        public PointClass()
        {
            x = 0; y = 0;
        }
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------        public static PointClass[] DeSortX(PointClass[] points)
        {
            int length = ;
            double temx, temy;
            for (int i = 0; i &lt; length - 1; i++)
            {
                for (int j = 0; j &lt; length - i - 1; j++)
                    if (points[j].x &gt; points[j + 1].x)
                    {

                        temx = points[j + 1].x;
                        points[j + 1].x = points[j].x;
                        points[j].x = temx;
                        temy = points[j + 1].y;
                        points[j + 1].y = points[j].y;
                        points[j].y = temy;
                    }
            }
            return points;
        }

    }

3. Lagrangian interpolation

(1) Unequal interpolation of one-yuan full range

        /// &lt;summary&gt;
        /// One-yuan full interval non-equidistance interpolation        /// Lagrangian interpolation algorithm        /// &lt;/summary&gt;
        /// <param name="x">One-dimensional array, length n, store the value x(i) of the given n nodes, requiring x(0)<x(1)<...<x(n-1)</param>        /// <param name="y">One-dimensional array, length n, store the function value y(i) of the given n nodes, y(i) = f(x(i)), i=0,1,...,n-1</param>        /// <param name="t">Storing the x value of the specified interpolation point</param>        /// <returns>The specified approximate value of the function to check t is y=f(t)</returns>        public static double Lagrange(double[] x, double[] y, double t)
        {
            // x,y points            int n = ;
            double z = 0.0;

            // Special case handling            if (n &lt; 1)
            {
                return (z);
            }
            else if (n == 1)
            {
                z = y[0];
                return (z);
            }
            else if (n == 2)
            {
                z = (y[0] * (t - x[1]) - y[1] * (t - x[0])) / (x[0] - x[1]);
                return (z);
            }

            // Start interpolation            int ik = 0;
            while ((x[ik] &lt; t) &amp;&amp; (ik &lt; n))
            {
                ik = ik + 1;
            }

            int k = ik - 4;
            if (k &lt; 0)
            {
                k = 0;
            }
            int m = ik + 3;
            if (m &gt; n - 1)
            {
                m = n - 1;
            }
            for (int i = k; i &lt;= m; i++)
            {
                double s = 1.0;
                for (int j = k; j &lt;= m; j++)
                {
                    if (j != i)
                    {
                        // Lagrangian interpolation formula                        s = s * (t - x[j]) / (x[i] - x[j]);
                    }
                }

                z = z + s * y[i];
            }

            return (z);
        }
         /// &lt;summary&gt;
        /// One-yuan full interval non-equidistance interpolation        /// &lt;/summary&gt;
        /// <param name="points">Point set (including XY coordinates)</param>        /// &lt;param name="t"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static double Lagrange(PointF[] points, double t)
        {
            double[] x = new double[];
            double[] y = new double[];
            for (int i = 0; i &lt; ; i++)
            {
                x[i] = points[i].X;
                y[i] = points[i].Y;
            }
            return Lagrange(x, y, t);
        }
        /// &lt;summary&gt;
        /// One-yuan full interval non-equidistance interpolation        /// &lt;/summary&gt;
        /// <param name="points">Set of point of binary type (including XY coordinates)</param>        /// &lt;param name="t"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static double Lagrange(List&lt;Tuple&lt;double, double&gt;&gt; points, double t)
        {
            double[] x = new double[];
            double[] y = new double[];
            for (int i = 0; i &lt; ; i++)
            {
                x[i] = points[i].Item1;
                y[i] = points[i].Item2;
            }
            return Lagrange(x, y, t);
        }
        /// &lt;summary&gt;
        /// Unequal interpolation of the whole interval of a single element is obtained to obtain the interpolated curve (polyline fitting) data        /// &lt;/summary&gt;
        /// <param name="points">Point set (including XY coordinates)</param>        /// <param name="segment_count">Number of segments per data segment</param>        /// &lt;returns&gt;&lt;/returns&gt;
        public static PointF[] Lagrange_Curve(PointF[] points, int segment_count = 10)
        {
            int n = ;
            PointF[] segments = new PointF[n * segment_count + 1];
            for (int i = 0; i &lt;  - 1; i++)
            {
                double dt = (points[i + 1].X - points[i].X) / segment_count;
                double t = points[i].X;
                for (int j = 0; j &lt;= segment_count; j++, t += dt)
                {
                    PointF p = new PointF(0.0F, 0.0F);
                     = (float)t;
                    if (j == 0)  = points[i].Y;
                    else if (j == segment_count)  = points[i + 1].Y;
                    else  = (float)(Lagrange(points, t));
                    segments[i] = p;
                }
            }
            return segments;
        }
         /// &lt;summary&gt;
        /// One-yuan full interval isometric interpolation        /// (Use non-isometric interpolation method)        /// &lt;/summary&gt;
        /// <param name="x0">Storage the value of the first node among n equidistant nodes</param>        /// <param name="step">Step of isometric node</param>        /// <param name="y">One-dimensional array, length n, store the function value y(i) of the given n nodes, y(i) = f(x(i)), i=0,1,...,n-1</param>        /// <param name="t">Storing the x value of the specified interpolation point</param>        /// <returns>The specified approximate value of the function to check t is y=f(t)</returns>        public static double Lagrange(double x0, double step, double[] y, double t)
        {
            double[] x = new double[];
            for (int i = 0; i &lt; ; i++, x0 += step)
            {
                x[i] = x0;
            }
            return Lagrange(x, y, t);
        }

(2) One-yuan full interval equidistance interpolation

        /// &lt;summary&gt;
        /// One-yuan full interval isometric interpolation        /// &lt;/summary&gt;
        /// <param name="x0">Storage the value of the first node among n equidistant nodes</param>        /// <param name="step">Step of isometric node</param>        /// <param name="y">One-dimensional array, length n, store the function value y(i) of the given n nodes, y(i) = f(x(i)), i=0,1,...,n-1</param>        /// <param name="t">Storing the x value of the specified interpolation point</param>        /// <returns>The specified approximate value of the function to check t is y=f(t)</returns>        public static double Lagrange_Equidistant(double x0, double step, double[] y, double t)
        {
            int n = ;
            double z = 0.0;
 
            // Special case handling            if (n &lt; 1)
            {
                return (z);
            }
            else if (n == 1)
            {
                z = y[0];
                return (z);
            }
            else if (n == 2)
            {
                z = (y[1] * (t - x0) - y[0] * (t - x0 - step)) / step;
                return (z);
            }
 
            // Start interpolation            int ik = 0;
            if (t &gt; x0)
            {
                double p = (t - x0) / step;
                ik = (int)p;
                double q = (float)ik;
                if (p &gt; q)
                {
                    ik = ik + 1;
                }
            }
            else
            {
                ik = 0;
            }
            int k = ik - 4;
            if (k &lt; 0)
            {
                k = 0;
            }
            int m = ik + 3;
            if (m &gt; n - 1)
            {
                m = n - 1;
            }
            for (int i = k; i &lt;= m; i++)
            {
                double s = 1.0;
                double xi = x0 + i * step;
 
                for (int j = k; j &lt;= m; j++)
                {
                    if (j != i)
                    {
                        double xj = x0 + j * step;
                        // Lagrangian interpolation formula                        s = s * (t - xj) / (xi - xj);
                    }
                }
 
                z = z + s * y[i];
            }
 
            return (z);
        }

4. Hermit interpolation

(1) Hermit's unequal interpolation

        /// &lt;summary&gt;
        /// Hermit's non-equidistant interpolation        /// &lt;/summary&gt;
        /// <param name="x">One-dimensional array, length n, store the value x(i) of the given n nodes, requiring x(0)<x(1)<...<x(n-1)</param>        /// <param name="y">One-dimensional array, length n, store the function value y(i) of the given n nodes, y(i) = f(x(i)), i=0,1,...,n-1</param>        /// <param name="dy">One-dimensional array, length n, store the function derivative value y'(i), y'(i) = f'(x(i)), i=0,1,...,n-1</param>        /// <param name="t">Storing the x value of the specified interpolation point</param>        /// <returns>The specified approximate value of the function to check t is y=f(t)</returns>        public static double Hermite(double[] x, double[] y, double[] dy, double t)
        {
            int n = ;
            double z = 0.0;

            // Loop interpolation            for (int i = 1; i &lt;= n; i++)
            {
                double s = 1.0;

                for (int j = 1; j &lt;= n; j++)
                {
                    if (j != i)
                    {
                        s = s * (t - x[j - 1]) / (x[i - 1] - x[j - 1]);
                    }
                }
                s = s * s;

                double p = 0.0;
                for (int j = 1; j &lt;= n; j++)
                {
                    if (j != i)
                    {
                        p = p + 1.0 / (x[i - 1] - x[j - 1]);
                    }
                }
                double q = y[i - 1] + (t - x[i - 1]) * (dy[i - 1] - 2.0 * y[i - 1] * p);
                z = z + q * s;
            }

            return (z);
        }
        /// &lt;summary&gt;
        /// Hermit isometric interpolation        /// (Use non-isometric interpolation method)        /// &lt;/summary&gt;
        /// <param name="x0">Storage the value of the first node among n equidistant nodes</param>        /// <param name="step">Step of isometric node</param>        /// <param name="y">One-dimensional array, length n, store the function value y(i) of the given n nodes, y(i) = f(x(i)), i=0,1,...,n-1</param>        /// <param name="dy">One-dimensional array, length n, store the function derivative value y'(i), y'(i) = f'(x(i)), i=0,1,...,n-1</param>        /// <param name="t">Storing the x value of the specified interpolation point</param>        /// <returns>The specified approximate value of the function to check t is y=f(t)</returns>        public static double Hermite(double x0, double step, double[] y, double[] dy, double t)
        {
            double[] x = new double[];
            for (int i = 0; i &lt; ; i++, x0 += step)
            {
                x[i] = x0;
            }
            return Hermite(x, y, dy, t);
        }

(2) Hermit isometric interpolation

        /// &lt;summary&gt;
        /// Hermit isometric interpolation        /// &lt;/summary&gt;
        /// <param name="x0">The value of the first node among n equidistant nodes</param>        /// <param name="step">Step of isometric node</param>        /// <param name="y">One-dimensional array, length n, store the function value y(i) of the given n nodes, y(i) = f(x(i)), i=0,1,...,n-1</param>        /// <param name="dy">One-dimensional array, length n, store the function derivative value y'(i), y'(i) = f'(x(i)), i=0,1,...,n-1</param>        /// <param name="t">Storing the x value of the specified interpolation point</param>        /// <returns>The specified approximate value of the function to check t is y=f(t)</returns>        public static double Hermite(double x0, double step, double[] y, double[] dy, double t)
        {
            int n = ;
            double z = 0.0;
 
            // Loop interpolation            for (int i = 1; i &lt;= n; i++)
            {
                double s = 1.0;
                double q = x0 + (i - 1) * step;
                double p;
                for (int j = 1; j &lt;= n; j++)
                {
                    p = x0 + (j - 1) * step;
                    if (j != i)
                    {
                        s = s * (t - p) / (q - p);
                    }
                }
                s = s * s;
 
                p = 0.0;
                for (int j = 1; j &lt;= n; j++)
                {
                    if (j != i)
                    {
                        p = p + 1.0 / (q - (x0 + (j - 1) * step));
                    }
                }
                q = y[i - 1] + (t - q) * (dy[i - 1] - 2.0 * y[i - 1] * p);
                z = z + q * s;
            }
 
            return (z);
        }

This is the end of this article about the implementation example of C# linear interpolation. For more related C# linear interpolation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!