load_package gentran; gentranlang!* := 'c; on getdecs,double; func:=x*exp(-x)-1/5; gentranout "f.i"; gentran real procedure f(x); begin return eval(func); end; gentran real procedure df(x); begin return eval(df(func,x)); end;create the file f.i containing the lines
double f(x)
double x;
{
return((-exp(x)+5.0*x)/(5.0*exp(x)));
}
double df(x)
double x;
{
return((-x+1.0)/exp(x));
}
Our C program now becomes
#include <stdio.h>
#include <math.h>
#include "f.i"
double g(double x){
return x-f(x)/df(x);
}
int main(){
double x=2;
int i;
for(i=0;i<10;i++){
x=g(x);
printf("x=%24.15e\n",x);
}
return 0;
}
and the output is exactly the same as before.
The entire process of running the reduce script and building the executable can be automated using make with the Makefile
all: newton clean: rm -f f.i newton f.i: makeinc.red rm -f f.i /nfs/home/ejolson/opt/bin/reduce <makeinc.red newton: newton.c f.i gcc -o newton newton.c -lmNow changing the function definition in the reduce script and typing make automatically creates an executable which implements Newton's method for the new function.