Code:
#include <stdio.h>#include <stdlib.h>
#include <math.h>
#define pi 4. * atan(1.)
int LaGrange(int x0[],int x[],int n,int m);
main(){
double x[10]={0,0.1,0.3,0.45,0.66,0.8,1.1,1.4,1.5,1.9};
double approx[6]={-0.5,0.2,0.9,1.6,2.0,3.0};
double y[10],yapprox[6],lagrange[6],temp,total;
int i,n,m;
for(i=0;i<10;i++)
y[i]=x[i]*sin(x[i]);
for(i=0;i<7;i++)
yapprox[i]=approx[i]*sin(approx[i]);
for (m=0;m<=6;m++){
for (n=0;n<=9;n++){
if (n<=7){
temp=(((approx[n]-x[n+1])*(approx[n]-x[n+2]))/((x[n]-x[n+1])*(x[n]-x[n+2])))*y[n];
total += temp;
}
else{
temp=(((approx[n]-x[n-1])*(approx[n]-x[n]))/((x[n-2]-x[n-1])*(x[n-2]-x[n])))*y[n];
total += temp;
}
}
lagrange[m]=total;
}
printf("\nThe LaGrange Values for each value:\n");
printf("x=-.5:\t%e\nx=0.2:\t%e\nx=0.9:\t%e\nx=1.6:\t%e\nx=2.0:\t%e\nx=3.0:\t%e\n",lagrange[0],lagrange[1],lagrange[2],lagrange[3],lagrange[4],lagrange[5]);
printf("\nThe actual value for each value is:\n");
printf("x=-.5:\t%e\nx=0.2:\t%e\nx=0.9:\t%e\nx=1.6:\t%e\nx=2.0:\t%e\nx=3.0:\t%e\n",yapprox[0],yapprox[1],yapprox[2],yapprox[3],yapprox[4],yapprox[5]);
getchar();
}
So I am suppose estimate the values for xsinx by using Lagrange polynomial and noticed while doing this that my code is almost correct but my equation is not 9th order. How can i make my code shorter instead of writing out a 9th order polynomial. The equation i made was a 2nd order because i was not really understanding the LaGrange Polynomial.
I basically have learning arrays, pointers, functions and thats it for right now. I can't use structures for this (I don't know what they are either.
This is what a LaGrange Polynomial is.
lagrange polynomial - Wolfram|Alpha
Thank you for all the help