几种插值算法的代码实现
来源:互联网 发布: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
- 几种插值算法的代码实现
- CRC算法的代码实现
- 排列组合算法的实现代码
- [原创]TEA算法的VB实现代码
- KMP算法的C语言代码实现
- kmp算法的c代码实现
- 几种排序算法的实现代码
- 判断回文算法的代码实现
- KMP算法的C++实现代码
- 堆排序算法的C++实现代码
- 《算法导论》中BTree的代码实现~
- 简单的排序算法代码实现
- DES算法的C实现代码
- Hog算法加速的实现代码
- KMP算法的代码实现一
- python实现的各种排序算法代码
- 算法导论 红黑树的C++代码实现
- Java实现最大公约数的算法代码
- 使用ZendFramework创建工程
- #ifdef 和 #if defined 的区别
- ScrollView中用ListView的事件冲突
- grep 命令变色
- poj 1681 Painter's Problem (高斯消元)
- 几种插值算法的代码实现
- 湖南省第六届大学生程序竞赛--战场的数目
- Property Animation Part II(属性动画 第二部分)
- activeMQ性能优化--对象池管理connection
- objc语言的运行时处理
- ios音视频相关牛人
- Android 自定义View (TextView)
- 扫描二维码自动识别手机APP下载地址
- 安装 xmlbuddy 插件到 Eclipse 3.0 以支持编辑 xml 文件