Sunday, August 08, 2010

Newton's Method


My recent implementation of Newton's method. Was bored. Figured I'd review.

The following code is for finding some of the roots of the sin() function. It's a very basic example.







The code:
#include
#include
#include

double f (double);
double fp (double);
double next_x (double);

int main(int argc, char **argv)
{
int iteration = 0;
if ( argc == 1 )
{
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(1);
}
double x = atoi( argv[1] );

do
{
x = next_x(x);
printf("%f 0\n", x);
} while ( iteration++ <= 10 );

return(0);
} /* end main() */

double next_x (double x) { return(x-(f(x)/fp(x))) }
double f (double x) { return( sin(x) ) }
double fp (double x) { return( cos(x) ) }

Makefile:
CC=/usr/bin/gcc LIBS=-lm all: ${CC} -Wall ${LIBS} -o roots roots.c clean: rm -f roots roots.out

Command line:
for num in -5 -4.5v-4 -3.5 -3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5; do ./roots ${num} | tail -1; done > roots.out

Gnuplot:
plot [-20:20] [-1.5:1.5] sin(x), 'roots.out' using 1:2

0 Comments:

Post a Comment

<< Home