#include "header.h" //Compute the Gradient! //There are some commented out sections; to compute a function differently, recomment out blocks. // vector * vecin The inputed vector, cloned into vector alterposi // vector * df The gradient vector, filled as this gradfunk evaluates. // double result The result of the initial function evaluation // Usefull if using the central difference. // double interval The interval; how we farstep from x to calculate slope void gradfunk(vector * vecin, vector * df, double result, double interval) { //vecin and df should have the same size. int n = vecin->size, i; //We need a slightly altered vector to see how f changes with x. //We shall call it alterposi if it is a positive increase. // vector alternegi = craftvec(n, vecin->elements); vector alterposi = craftvec(n, vecin->elements); vector thrashdata = craftvecEZ(n);//Holds the parts of the function during evaluation. Not used for anything beyond that. for (i=0; i< n; i++) { // alternegi.elements[i] -= interval; alterposi.elements[i] += interval;//Edit the interval. // df->elements[i] = ( sumfunk(&alternegi,&thrashdata) - sumfunk(&alternegi,&thrashdata) ) / (2*interval); //Calculate the central difference. // df->elements[i] = ( result - sumfunk(&alternegi,&thrashdata) ) / (interval); //Calculate the backward difference. df->elements[i] = ( sumfunk(&alterposi,&thrashdata) - result ) / (interval); //Calculate the forward difference. //alternegi.elements[i] = vecin->elements[i]; alterposi.elements[i] = vecin->elements[i];//Restore the altered vec so we're ready for the next calculation } destroyvec(&thrashdata); //Free the garbage data. destroyvec(&alterposi); //Free the positively altered vector // destroyvec(alternegi); //Free the negatively altered vector return; }