用C语言编写一个线性插值程序

用C语言编写一个线性插值程序,第1张

#include <stdio.h>

double Lerp(double x0,double y0,double x1,double y1,double x)

{

    double dy = y1 - y0

    if(dy == 0){

        printf("除0错误!\n")

        return 0

    }

    return x * (x1 - x0) / dy

}

int main()

{

    double x0,x1,y1,y0,x,y

    printf("Inptu x0 y0 x1 y1 x:")

    scanf("%lf %lf %lf %lf %lf",&x0,&y0,&x1,&y1,&x)

    y = Lerp(x0,y0,x1,y1,x)

    printf("y = %lf\n",y)

    return 0

}

clear

clc

x=[0.0, 0.1, 0.195, 0.3, 0.401, 0.5]

f=[0.39894,0.39695,0.39142,0.38138,0.36812,0.35206]

x_in = str2double(inputdlg('Enter X data:','Input Data',1,{'0.2'}))

for i=1:5

if x(i) <= x_in &&x(i + 1) >= x_in

f_out = (f(i) * x(i) + f(i+1) * x(i+1)) / (x(i) + x(i+1))

break

end

end

fprintf('f(%f)=%f\n',x_in,f_out)

还可以这样写代码,完全利用matlab的矩阵优势,而且没有调用任何函数:

clear

clc

x=[0.0, 0.1, 0.195, 0.3, 0.401, 0.5]

f=[0.39894,0.39695,0.39142,0.38138,0.36812,0.35206]

x_in = str2double(inputdlg('Enter X data:','Input Data',1,{'0.2'}))

index=(x(1:end-1) <= x_in &x_in <= x(2:end)) * (1:5)' * [1,1] + [0,1]%下标数值

f_out = f(index) * x(index)' / sum(x(index))

fprintf('f(%f)=%f\n',x_in,f_out)

///<summary>

///分段线性插值,将一组数插值为所需点数

///</summary>

///<param name="dataIn">待插值的数据数组</param>

///<param name="n">插值点数</param>

///<returns>插值后的数据数组</returns>

public static double[] Interpolation(double[] dataIn,int n)

{

double[] dataOut = new double[n]

int lenIn = dataIn.Length

double[] a = new double[lenIn]

double[] divIn = new double[lenIn]

double[] divOut = new double[n]

divIn[0] = 0

for (int i = 1i <lenIni++)

{

divIn[i] = divIn[i - 1] + 1

}

divOut[0] = 0

for (int i = 1i <ni++)

{

divOut[i] = divOut[i - 1] + lenIn / Convert.ToDouble(n)

}

int k = 0

for (int i = ki <ni++)

{

for (int j = 0j <lenIn - 1j++)

{

if (divOut[i] >= divIn[j] &&divOut[i] <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

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11157509.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存