拉格朗日插值公式---读题题

Lagrange’s Interpolation

What is Interpolation?
Interpolation is a method of finding new data points within the range of a discrete set of known data points (Source Wiki). In other words interpolation is the technique to estimate the value of a mathematical function, for any intermediate value of the independent variable.
For example, in the given table we’re given 4 set of discrete data points, for an unknown function f(x) :

example

How to find?
Here we can apply the Lagrange’s interpolation formula to get our solution.
The Lagrange’s Interpolation formula:
If, y = f(x) takes the values y0, y1, … , yn corresponding to x = x0, x1 , … , xn then,

f(x) = \tfrac{(x-x_2)(x-x_3)...(x-x_n)}{(x_1-x_2)(x_1-x_3)...(x_1-x_n)}y_1 + \tfrac{(x-x_1)(x-x_3)...(x-x_n)}{(x_2-x_1)(x_2-x_3)...(x_2-x_n)}y_2+ ..... + \tfrac{(x-x_1)(x-x_2)...(x-x_n_-1)}{(x_n-x_1)(x_n-x_2)...(x_n-x_n_-1)}y_n

This method is preferred over its counterparts like Newton’s method because it is applicable even for unequally spaced values of x.

We can use interpolation techniques to find an intermediate data point say at x = 3.

 

题意描述:给出一个公式,输入x,求出相对应的f(x)

题目样例:

输入 0,输出2

输入 5,输出147

输入 3,输出35

相关代码:----其实看代码这个思路非常简单,只需要读对题目~~~ 

#include<iostream>
using namespace std;
struct Data{
	int x,y;
};
double solve(int xi,Data fi[],int n)
{
	double result=0; 
	for(int i=0;i<n;i++)
	{
		double t=fi[i].y;
		for(int j=0;j<n;j++)
		{
			if(i!=j)
			{
				t=t*(xi-fi[j].x)/(fi[i].x-fi[j].x);
			} 
		}
		result+=t;
	}
	return result;
}
int main(){
	Data fi[]={{0,2},{1,3},{2,12},{5,147}};
	int xi;
	cin>>xi;
	cout<<solve(xi,fi,5);
}

The time complexity of the above solution is O(n2) and auxiliary space is O(1).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值