代码
#include<iostream>
using namespace std;
double Newton(double x[], double y[], double t, int n)
{
double *x2 = new double [n];
double *y2 = new double [n];
double *Separated = new double[((1 + n)*n) / 2];
int dot=0;
int i;
for ( dot; t>x[dot]; dot++);//find t position
cout << "find out dot:" << dot << endl;
if (dot <= n / 2) {
cout << "1.find dot should in";
for (int j = 0; j<n; j++)
cout << j << " ";
cout << endl;
i = 0;
for (; i<n; i++)
{
x2[i] = x[i];
y2[i] = y[i];
}
}
else if (dot >= 20 - n / 2 + 1)
{
cout << "2.find dot should in";
for (int j = 20 - n; j<20; j++)
cout << j << " ";
cout << endl;
i = 20 - n ;
int q = 0;
for (i; i<20; i++)
{
x2[q] = x[i];
y2[q] = y[i];
q++;
}
}
else {
cout << "3.find dot should in";
for (int j = dot - 4; j<dot+4; j++)
cout << j << " ";
cout << endl;
i = dot - 4;
int q = 0;
for (i; i<dot+4; i++)
{
x2[q] = x[i];
y2[q] = y[i];
q++;
}
}
static int num = 0;
cout << x2[0] << "\t\t" << y2[0] << "\t\t" << endl;
for (int i = 1; i < n; i++)
{
cout << x2[i] << "\t\t" << y2[i] << "\t\t";
if(i >= 1)
{
Separated[num] = (y2[i]-y2[i-1])/(x2[i]-x2[i-1]);
cout << Separated[num] << "["<<num<<"]\t\t";
num++;
}
if (i >= 2)
{
Separated[num] = (Separated[num - 1] - Separated[num - i]) / (y2[i] - y2[i - 1]);
cout << Separated[num] << "[" << num << "] \t\t";
num++;
}
while (i >= 3)
{
for (int j = 1; j <= i - 2; j++)
{
Separated[num] = (Separated[num - j] - Separated[num - i]) / (Separated[num - j - 1] - Separated[num - i - 1]);
cout << Separated[num] << "[" << num << "]\t\t";
num++;
}
break;
}
cout << endl;
}
double fx = x2[0];
double w;
double q = 1;
int n1=0;
for (int i = 0; i < n-1; i++)
{
w = t - x[i];
q = q*w;
fx = fx + q*Separated[n1];
cout <<"N1="<<n1<< "\t\toutput:fx=" << fx << endl;
n1 = n1 + 2 + i;
}
return 0;
}
int main()
{
double x[] = { 0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00,1.05 };
double y[] = { 0.1103329,0.1736223,0.2426552,0.3176729,0.3989105,0.4865951,0.5809439,0.6821617,0.7904390,0.9059492,
1.0288456,1.1592592,1.2972951,1.4430292,1.5965053,1.7577308,1.9266733,2.1032563,2.2873552,2.4787929 };
int n = 8;
double t;
cout << "请输入待求点" << endl;
cin >> t;
Newton(x, y, t, n);
system("pause");
return 0;
}