C语言实现三次样条插值

算法推导过程参考:
https://wenku.baidu.com/view/88c5af9f185f312b3169a45177232f60dccce772.html?rec_flag=default&fr=pc_newview_relate-1001_1-3-wk_rec_doc2-1001_1-3-88c5af9f185f312b3169a45177232f60dccce772&sxts=1609484456691

#include <stdio.h>


# define MAX_N 20             // 定义(x_i,y_i)的最大的维数  

typedef struct tagPOINT         // 插值点的结构体成员有x, y
{
	double x;
	double y;
} POINT;

POINT points[MAX_N + 1];
//需要拟合的六个点(x0 y0 x1 y1...)
double passData[12] = { 0, 0, 1, 2.15, 2, 12.1, 3, 32.9, 4, 42.87, 5, 45 };

int i, j, k, n, num;
double h[MAX_N + 1], b[MAX_N + 1], c[MAX_N + 1], d[MAX_N + 1], M[MAX_N + 1];
double u[MAX_N + 1], v[MAX_N + 1], y[MAX_N + 1];

//计算M矩阵
void CaculateM(void) {
	num = sizeof(passData) / sizeof(passData[0]);	//获取数组元素个数
	n = num / 2;	//获取x个数
	M[0] = M[n] = 0;	//自然边界

	for (i = 0; i < num; i += 2) {
		points[j].x = passData[i];
		points[j].y = passData[i + 1];
		j++;
	}
	// 计算M关系式中各参数的值  
	h[0] = points[1].x - points[0].x;
	for (i = 1; i<n; i++) {
		h[i] = points[i + 1].x - points[i].x;
		b[i] = h[i] / (h[i] + h[i - 1]);
		c[i] = 1 - b[i];
		d[i] = 6 * ((points[i + 1].y - points[i].y) / h[i] - (points[i].y - points[i - 1].y) / h[i - 1]) / (h[i] + h[i - 1]);
	}
	// 用追赶法计算Mi,i=1,…,n-1  
	d[1] -= c[1] * M[0];
	d[n - 1] -= b[n - 1] * M[n];
	b[n - 1] = 0; c[1] = 0; v[0] = 0;
	for (i = 1; i<n; i++) {
		u[i] = 2 - c[i] * v[i - 1];
		v[i] = b[i] / u[i];
		y[i] = (d[i] - c[i] * y[i - 1]) / u[i];
	}
	for (i = 1; i<n; i++) {
		M[n - i] = y[n - i] - v[n - i] * M[n - i + 1];
	}
}

//计算要插值的x对应的y值
double Spline(double spline_x) {
	double p, q, S;
	M[0] = M[n] = 0;

	while (spline_x >= points[k].x) k++;
	k = k - 1;
	p = points[k + 1].x - spline_x;
	q = spline_x - points[k].x;
	S = (p* p* p* M[k] + q* q* q* M[k + 1]) / (6 * h[k]) + (p* points[k].y + q*points[k + 1].y) / h[k] - h[k] * (p* M[k] + q* M[k + 1]) / 6;

	return S;
}

int main() {
	double ret;

	CaculateM();
	ret = Spline(3);
	printf("result = %f\n", ret);
	// 输出 

	system("pause");
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值