Skip to main content
Logo image

Section 31.2 Building a Root-Finding Library

Rather than hard-coding Newton’s method for one specific function, let’s write a generic Newton’s method that accepts any math equation via a callback— this way it can be reused for any function \(f\text{,}\) as long as we can supply its value and derivative. We’ll put it in its own library, rootfinding, made up of a header file and a source file, with the following prototype:
void newton(void (*func) (double, double *, double*), double x0, double *root);
Here is the header file:

admin.....open in new window

And here is the source file, which finds the root iteratively using the formula from the previous section:

admin.....open in new window

Call your newton() function from main() and print the result. Since this involves multiple files, we cannot use the compile script for this exercise— you’ll need to compile manually, the same way we did for the Complex Number Library:
gcc -c -o rootfinding.o rootfinding.c
gcc -c -o main.o main.c
gcc -o main main.o rootfinding.o -lm
Test your code with a second function, \(g(x) = e^x - 10\text{,}\) starting again from \(x_0 = 10\text{.}\)