I have an assignment to write code to calculate a cubic spline. The values for my coefficients are correct, but the Gaussian elimination part of my program has me really confused. I was given code in C by my instructor, but am struggling in making it work with my code.
If anyone has any suggestions I would GREATLY appreciate it!
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <fstream.h>
void main() {
int n = 4;
double x[4];
double y[4];
double matrix[4][4];
double a[4][4];
double b[4];
int i, j, m;
double ratio, temp;
int count;
for (m=0; m<n; m++) {
for(i=0; i<n; i++) {
a[m][i]=0.0;
}
}
x[0]=1;
y[0]=1;
x[1]=2;
y[1]=.5;
x[2]=3;
y[2]=1/3;
x[3]=4;
y[3]=.25;
// this portion works fine and the results check out....
j=1;
for(m = 1; m<n-1; m++) {
a[m][j-1] = (x[j]-x[j-1])/6;
a[m][j] = (x[j+1]-x[j-1])/3;
a[m][j+1] = (x[j+1]-x[j])/6;
b[m] = ((y[j+1]-y[j])/(x[j+1]-x[j]))-((y[j]-y[j-1])/(x[j]-x[j-1]));
cout << a[m][j-1] << " M[" << m << "][" << j-1 << "] + ";
cout << a[m][j] << " M[" << m << "][" << j << "] + ";
cout << a[m][j+1] << " M[" << m << "][" << j+1 << "] ";
cout << " = " << b[m] << endl << endl;
j++;
}
// Here's where the problems begin... I just get garbage data...
/* Gaussian Elimination (provided by instructor) */
for(i=1;i<(n-1);i++){
for(j=(i+1);j<n;j++){
ratio = a[j][i] / a[i][i];
cout << "ratio " << a[j][i] << "/" << a[i][i] << " = " << ratio << endl;
for(count=i;count<n;count++) {
a[j][count] -= (ratio * matrix[i][count]);
cout << "a[" << j << "][" << count << "] = " << a[j][count] << endl;
}
b[j] -= (ratio * b[i]);
cout << "b[" << j << "] = " << b[j] << endl;
}
}
for (i=0;i<=n-1;i++){
for(j=0;j<n;j++){
cout << matrix[i][j] << endl;
}
}
/* Back substitution */
x[n-1] = b[n-1] / matrix[n-1][n-1];
for(i=(n-2);i>=0;i--){
temp = b[i];
for(j=(i+1);j<n;j++){
temp -= (matrix[i][j] * x[j]);
}
x[i] = temp / matrix[i][i];
}
cout << "Answer:" << endl;
for(i=0;i<n;i++){
cout << "x[" << i << "] = " << x[i] << endl;
}
return;
}