functions/root-c-doc-1-doxy.c - Dokumentation af funktionerne i rodsøgningsprogrammet - beregnet for Doxygen. | Lektion 7 - slide 22 : 25 Program 5 |
/* A program that finds a root in a continuous function f by use of the * bisection method. * Programmer: Kurt Normark, Aalborg University, normark@cs.aau.dk. * Version 0.9, September 15, 2010. */ #include <stdio.h> #include <math.h> /** The function in which we search for a root. @param[in] x The input to the function f. */ double f (double x){ /* (x - 5.0) * (x - 3.0) * (x + 7.0) */ return (x*x*x - x*x - 41.0 * x + 105.0); } /** Return whether x and y have the same sign. @param[in] x The first double the sign of which is to be compared with y. @param[in] y The second double the sign of which is to be compared with x. @return A boolean represented as an int in C (false = zero, true = non zero). */ int sameSign(double x, double y){ return (x > 0 && y > 0) || (x < 0 && y < 0); } /** Return the mid point in between x and y. @param[in] x The first double. @param[in] y The second double. */ double middleOf(double x, double y){ return x + (y - x)/2; } /** Is x considered to be very close to 0.0. @param[in] x The input to be evaluated. @return A boolean represented as an int in C (false = zero, true = non zero). */ int isSmallNumber(double x){ return (fabs(x) < 0.0000001); } /** Search for a root of the continuous function f between the parameters l and u. A root is a double r for which f(r) is very close to 0.0. @param[in] l The lower limit of the interval in which to search for a root. @param[in] u The upper limit of the interval in which to search for a root. @return The x-value r for which f(x) is close to zero. @pre The sign of f(l) and f(u) are different. */ double findRootBetween(double l, double u){ while (!isSmallNumber(f(middleOf(l,u)))){ if(sameSign(f(middleOf(l,u)), f(u))) u = middleOf(l,u); else l = middleOf(l,u); } return middleOf(l,u); } /** A sample interactive driver of the root searching for f. */ int main (void){ double x, y; int numbers; do{ printf("%s","Find a ROOT between which numbers: "); numbers = scanf("%lf%lf", &x, &y); if (numbers == 2 && !sameSign(f(x),f(y))){ double solution = findRootBetween(x,y); printf("\nThere is a root in %lf\n", solution); } else if (numbers == 2 && sameSign(f(x),f(y))) printf("\nf must have different signs in %lf and %lf\n", x, y); else if (numbers != 2) printf("\nBye\n\n"); } while (numbers == 2); return 0; }