| functions/root-c-doc-1.c - Dokumentation af program og funktioner i rødsøgingsprogrammet. | Lektion 7 - slide 22 : 25 Program 2 |
/* 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 */
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 */
int sameSign(double x, double y){
return (x > 0 && y > 0) || (x < 0 && y < 0);
}
/* Return the mid point in between x and y */
double middleOf(double x, double y){
return x + (y - x)/2;
}
/* Is x considered to be very close to 0.0 */
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. As a
precondition it is assumed that 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;
}