1 //Topic Requirements:interpolation using Newton's difference quotient formula2#include <iostream>3#include <cmath>4#include <cstring>5 using namespacestd;6 #defineNUMOFX 20//define the size of the data volume7 structdata{8 Doublex;9 DoubleFx//defines the point at which the operation is performed (X,FX)Ten }POINTDATA[NUMOFX]; One A //the formula of finding the difference quotient F (X0,X1,X2...XN) - Long DoubleChashang (intN) {//calculation F[x0,x1,x2...xn] - if(n<=0){ the return 0; - } - - Long Doubleresult=0; + for(intI=0; i<=n;i++){ - //calculate the 0~n of the computed value of this + Long Doubleresproduct=1; A for(intj=0; j<=n;j++){ at if(j!=i) { -Resproduct*= (pointdata[i].x-pointdata[j].x); - } - } - Long Doubletemp=pointdata[i].fx/resproduct; -result+=temp; in } - returnresult; to } + - intMain () { the intNumofpoint; *cout<<"The number of interpolated points that will be entered is:"; $Cin>>Numofpoint;Panax Notoginsengcout<<"Please enter the value of X,FX: \ n"; - for(intI=0; i<numofpoint;i++){ theCin>>pointdata[i].x>>pointdata[i].fx; + } A the //Print output Newton difference quotient formula, not simple +cout<<"The Newton interpolation polynomial calculated from the above interpolation points is: \ n"; -cout<<"f (x) ="<<pointdata[0].fx; $ for(intI=1; i<numofpoint;i++){ $ Long Doubletemp4=Chashang (i); - if(temp4>=0){ -cout<<"+"<<temp4<<"*"; the } - Else{Wuyicout<<temp4<<"*"; the } - Wu for(intj=0; j<i;j++){ -cout<<"(X-"<<pointdata[j].x<<")"; About } $ } - - //calculate Newton interpolation polynomial approximation of an x - Doublex; Acout<<"\ n \ nyou Enter the value of the variable x to be evaluated:"; +Cin>>x; thecout<<"The approximate result of Newton interpolation polynomial is:"; - $ Long Doubleres=pointdata[0].fx;//the F (x0) term of Newton's difference quotient formula the for(intI=0; i<numofpoint-1; i++) {//Newton interpolation polynomial term f[x0,x1...xn] (x-x0) (x-x1) ... (X-XN) N>=1 the the Long Doubletemp=1; the for(intj=0; j<=i;j++){ -temp=temp* (xpointdata[j].x); in } the theRes=res+chashang (i+1)*temp; About } thecout<<res<<Endl; the}
Lagrange Interpolation procedure:
1#include <iostream>2#include <fstream>3 using namespacestd;4 5 classlagrange{6 7 Private:8 intI,j,n;9 Doublemult,sum,z;Ten Double*x,*y; One A Public: - voidinterpolation () { -Ifstream Fin ("a.txt"); theFin>>N; -x=New Double[n]; -y=New Double[n]; - for(i=0; i<n;i++){ +Fin>>x[i]>>Y[i]; - } + fin.close (); Acout<<"\ n Enter the points that need to be interpolated:"; atCin>>Z; -sum=0.0; - - for(i=0; i<n;i++){ -mult=1.0; - for(j=0; j<n;j++){ in if(j!=i) { -Mult*= (Z-x[j])/(x[i]-x[j]); to } + } -sum+=mult*Y[i]; the } *cout<<"\ n interpolated value ="<<sum<<Endl; $ Panax Notoginseng } - the~Lagrange () { + Delete[] x, y; A } the + }; - $ intMain () { $ Lagrange Interp; - interp.interpolation (); -}
Newton interpolation polynomial