C语言实现拉格朗日插值法
生活随笔
收集整理的這篇文章主要介紹了
C语言实现拉格朗日插值法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
? ? ? ? 由于本學期有一門計算方法的課需要C語言編程,在這里記錄一下。
? ? ? ? 由于這是第一章且后面的課大約也有相似的屬性,比如對n個點的使用和函數(shù)的調(diào)用,這里就進行一個小封裝,方便以后吃老本。
? ? ? ? 歡迎需要參考的同學復制粘貼,互相交流.
//POINTS.h #pragma once #include<vector> using namespace std; #ifndef _POINTS_ #define _POINTS_ class POINTS { public:typedef struct MYPOINT{double x;double y;}mypoint;int len;int size;virtual void run(double val);virtual void loaddata(double* vallist); }; #endif // !_POINTS_ //POINTS.cpp #include "POINTS.h" #include<iostream> using namespace std; void POINTS::run(double val) {cout << "計算函數(shù)" << endl; } void POINTS::loaddata(double* vallist) {cout << "數(shù)據(jù)處理函數(shù)" << endl; } //LAGRANGE.h #pragma once #include "POINTS.h" #ifndef _LAGRANGE_ #define _LAGRANGE_ class LAGRANGE :public POINTS { public:LAGRANGE(int n);vector<mypoint> datalist;virtual void run(double val);virtual void loaddata(double* vallist); }; #endif // !LAGRANGE //LAGRANGE.cpp #include "LAGRANGE.h" #include<iostream> using namespace std; LAGRANGE::LAGRANGE(int n):datalist(n) {this->size = n;this->len = 0; } void LAGRANGE::run(double val) {double sum = 0.0;vector<double> templist;for (size_t i = 0; i < this->size; i++){double tempval = 1.0;for (size_t j = 0; j < this->size; j++){if (j != i)tempval *= ((val - this->datalist.at(j).x) /(this->datalist.at(i).x - this->datalist.at(j).x));elsecontinue;}templist.push_back(tempval);}for (size_t i = 0; i < this->size; i++){sum += this->datalist.at(i).y * templist.at(i);}cout << "拉格朗日" << this->size << "項插值計算為:" << sum << endl; }void LAGRANGE::loaddata(double* vallist) {cout << "正在處理數(shù)據(jù)..." << endl;for (size_t i = 0; i < this->size * 2; i++){if (((i + 1) % 2) == 0){this->datalist.at(this->len).y = vallist[i];this->len++;}else{this->datalist.at(this->len).x = vallist[i];}} } //main.cpp #include<iostream> #include"POINTS.h" #include"LAGRANGE.h" using namespace std; int main() {cout << "例1" << endl;//實例化工具類LAGRANGE lgr(2);//構建運算參數(shù)表double val[4] = { 100.0,10.0,121.0,11.0 };//調(diào)用處理數(shù)據(jù)函數(shù)lgr.loaddata(val);//傳入目標x運算,例1lgr.run(115);//傳入目標x運算,例2cout << "例2" << endl;LAGRANGE lgr1(3);double val1[6] = { 100.0,10.0,121.0,11.0,144.0,12.0 };lgr1.loaddata(val1);lgr1.run(115);//課上的題目求ln3.16cout << "求ln3.16" << endl;LAGRANGE lgr2(2);double val2[4] = { 3.1,1.1314,3.2,1.1632 };lgr2.loaddata(val2);lgr2.run(3.16);system("pause");return 0; }總結
以上是生活随笔為你收集整理的C语言实现拉格朗日插值法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IEEE PHM 2012挑战赛的轴承数
- 下一篇: 家具防窜货防伪RFID方案