The following short program is taken from a book in numerical analysis (by Mircea Andrecut). It's about bisection (very simple):
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double f(double x) { return x*x-3; }
double bisection(double f(double), double a, double b)
{
double epsilon = 1E-7, x;
int kmax, k;
if (f(a)*f(b) > 0) { printf("\n ERROR f(a)*f(b) > 0 !"); exit(1); }
kmax = (int)(1+log((b-a)/epsilon)/log(2));
for (k = 0; k < kmax; k++) { x=0.5*(a+b); if(f(x)*f(a)>0) a = x; else b = x; }
return x;
}
int main(int argc, char* argv[])
{
double a, b, x;
printf("\n Enter the limits of the interval [a,b]\n");
printf(" a = "); scanf("%1f", &a);
printf(" b = "); scanf("%1f", &b);
x = bisection(f, a, b);
printf(" RESULTS:");
printf("\n The computed root of f(x) = 0 : x = %1f", x);
printf("\n The computed value of function: f(x) = %1f", f(x));
}
The program gives the correct result (x = 1.732051), but (and strange) independent of the values of a and b, for example if I type a=0 and b=0 I still get the value x = 1.73... and not the error message in the bisection function: ERROR f(a)f(b) > 0. (Clearly f(0)f(0) > 0). But if I go to the main() function and direcly write x = bisection(f,0,0) instead of x = bisection(f,a,b) I get the correct error message. Is there something wrong with the scanf() function? (compiled as: gcc -o bisection bisection.c)