The following example shows how to declare an external function that takes callback parameters. The external function is an implementation of Newton's method for finding a root of the given function, . The derivative of , fprime must also be provided. The initial guess is continuously improved until the absolute value of is less than or equal to the given tolerance. If a good solution cannot be found in 100 iterations, the computation aborts and 0 is returned, otherwise the improved guess is returned. The external C function is defined as follows.
#include <stdio.h>
|
#include <math.h>
|
double newton(
|
double ( f ) (double),
|
double ( fprime ) (double),
|
double guess,
|
double tolerance )
|
{
|
int count = 0;
|
while( fabs(f(guess)) > tolerance && count++ < 100 )
|
guess = guess - f(guess)/fprime(guess);
|
return( count>=100 ? 0 : guess );
|
}
|
|
|
The Maple definition is:
>
|
|
Pick an equation and find its derivative.
| (1) |
| (2) |
The external function expects procedure arguments, so turn the above polynomials into procedures.
| (3) |
>
|
|
| (4) |
Call the external function to find the root.
>
|
|
| (5) |
Verify that this is a root.