Newton's Method

This is an advanced version of the Newton's method lab which automates the copy/paste we did with the mouse of the output from reduce into the C program. In particular, we use a slightly modified set of reduce commands to create a file f.i which can be included in our C program to define f and df. In particular, the reduce commands
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 -lm
Now changing the function definition in the reduce script and typing make automatically creates an executable which implements Newton's method for the new function.
Last Updated: Fri Sep 19 15:08:15 PDT 2014