几种插值算法的代码实现

来源:互联网 发布:seo待遇 编辑:程序博客网 时间:2024/06/06 14:22

  在学《计算方法》这门课程,跟随课堂进度,用C++代码实现课本中讲述的几种插值算法,权当练习。

  首先我们定义Point类

class Point{public:double x;double y;};

  对于每一个算法类,为了计算算法计算次数,所有都定义了以下成员变量及方法:

private:int m_calCount;void ZeroCalCount(){m_calCount = 0;}void CalCountAdd(){m_calCount++;}public:int GetCalCount(){return m_calCount;}

  在之后的算法代码中不予呈现

  作为测试插值效果,main函数中代码如下(不断更新):

(测试数据目前为f(x) = lnx 1-5 共五组数据)

int _tmain(int argc, _TCHAR* argv[]){Lagrange lag;Newton newt;int count;double x;cout << "Please input the number of points" << endl;cin >> count;Point *pt = new Point[count];for (int i = 0; i < count; i++)cin >> pt[i].x >> pt[i].y;cout << endl;while (1){cout << "Please input the number you want to calc" << endl;cin >> x;double lagResult = lag.Calc(x, count, pt);double newtResult = newt.Calc(x, count, pt);cout << endl;//newton-method and lagrange-method is basically identicalcout << "The lagrange-method result is " << lagResult << endl;cout << "Calculated " << lag.GetCalCount() << " times" << endl << endl;cout << "The newton-method result is " << newtResult << endl;cout << "Calculated " << newt.GetCalCount() << " times" << endl << endl;cout << endl;}system("pause");free(pt);return 0;}


1、Lagrange插值

class Lagrange{public:double Calc(double x, int count, Point pt[]){ZeroCalCount();double nume, deno, result = 0;for (int i = 0; i < count; i++){nume = 1;deno = 1;for (int j = 0; j < count; j++){if (i == j)continue;CalCountAdd(); nume *= x - pt[j].x;deno *= pt[i].x - pt[j].x;}result += (nume / deno) * pt[i].y;}return result;}};


2、Newton插值

class Newton{private://Calculate dq from x0 to xkdouble DQCalc(int k, Point pt[]){if (k == 0)return pt[0].y;double sum = 0, deno = 1;for (int i = 0; i <= k; i++){for (int j = 0; j <= k; j++){if (i == j)continue;CalCountAdd();<pre name="code" class="cpp">deno *= pt[i].x - pt[j].x;}sum += pt[i].y / deno;deno = 1;}return sum;}public:double Calc(double x, int count, Point pt[]){ZeroCalCount();double sum = 0, nume = 1;for (int i = 0; i < count; i++){if (i != 0)nume *= x - pt[i - 1].x;CalCountAdd();sum += DQCalc(i, pt) * nume;}return sum;}};


效果图:


0 0
原创粉丝点击