x= [1.2 , 1.25 , 1.30 , 1.40 , 1.45 , 1.50]
f= [[0.1823 , 0.2231 , 0.2624 ,0.3365 , 0.3716 , 0.4055 ],
求牛頓向前差除表 Pn(1.35)=?
程式
// CPP program for implementing
// Newton divided difference formula
#include <stdio.h>
// Function to find the product term
double proterm(int i, float value, float x[])
{
double pro = 1;
for (int j = 0; j < i; j++) {
pro = pro * (value - x[j]);
}
return pro;
}
// Function for calculating
// divided difference table
void dividedDiffTable(float x[], float y[][10], int n)
{
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
y[j][i] = (y[j][i - 1] - y[j + 1]
[i - 1]) / (x[j] - x[i + j]);
}
}
}
// Function for applying Newton's
// divided difference formula
double applyFormula(float value, float x[],
float y[][10], int n)
{
double sum = y[0][0];
for (int i = 1; i < n; i++) {
sum = sum + (proterm(i, value, x) * y[0][i]);
}
return sum;
}
// Function for displaying
// divided difference table
void printDiffTable(float y[][10],int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
printf(" %0.4lf\t", y[i][j]);
}
printf("\n");
}
}
// Driver Function
int main()
{
// number of inputs given
int n = 6;
float value, sum, y[10][10];
float x[] = { 1.2 , 1.25 , 1.30 , 1.40 , 1.45 , 1.50 };
// y[][] is used for divided difference
// table where y[][0] is used for input
// 0.1823 , 0.2231 , 0.2624 ,0.3365 , 0.3716 , 0.4055
y[0][0] = 0.1823;
y[1][0] = 0.2231;
y[2][0] = 0.2624;
y[3][0] = 0.3365;
y[4][0] = 0.3716;
y[5][0] = 0.4055;
// calculating divided difference table
dividedDiffTable(x, y, n);
// displaying divided difference table
printDiffTable(y,n);
// value to be interpolated
value = 1.35;
double result = applyFormula(value, x, y, n);
// printing the value
printf("\nValue at %.2lf is %.5lf ",value , result);
return 0;
}
輸出畫面
0.1823 0.8160 -0.3000 -0.0000 0.8002 -3.9997
0.2231 0.7860 -0.3000 0.2000 -0.3998
0.2624 0.7410 -0.2600 0.1001
0.3365 0.7020 -0.2400
0.3716 0.6780
0.4055
Value at 1.35 is 0.30016
沒有留言:
張貼留言