CBNSTF
CBNSTF
h>
#include <math.h> #include <math.h> #include <math.h>
double f(double x) { double f(double x) { double f(double x) {
return x * x - 4; } return x * x - 4; return x * x - 4;
int main() { } }
double a, b, c, error_tolerance; double f_derivative(double x) {
printf("Enter lower bound (a): "); int main() { return 2 * x;
scanf("%lf", &a); double a, b, c, error_tolerance; }
printf("Enter upper bound (b): ");
scanf("%lf", &b); int main() {
printf("Enter error tolerance: "); printf("Enter lower bound (a): "); double x0, x1, error_tolerance;
scanf("%lf", &error_tolerance); scanf("%lf", &a);
if (f(a) * f(b) >= 0) { printf("Enter upper bound (b): "); printf("Enter initial guess (x0): ");
printf("The function must have different signs at a and b.\n"); scanf("%lf", &b); scanf("%lf", &x0);
return 1; printf("Enter error tolerance: "); printf("Enter error tolerance: ");
} scanf("%lf", &error_tolerance); scanf("%lf", &error_tolerance);
do { do {
c = (a + b) / 2.0; if (f(a) * f(b) >= 0) { x1 = x0 - f(x0) / f_derivative(x0);
printf("c = %.6lf, f(c) = %.6lf\n", c, f(c)); printf("The function must have different signs at a and b.\n"); if (fabs(f(x1)) < error_tolerance) {
if (fabs(f(c)) < error_tolerance) { return 1; break;
break; } }
} x0 = x1;
if (f(c) * f(a) < 0) { do {
b = c; } while (fabs(f(x1)) >= error_tolerance);
} else { c = (a * f(b) - b * f(a)) / (f(b) - f(a)); printf("Root: x = %.6lf\n", x1);
a = c; printf("f(x) = %.6lf\n", f(x1));
}
} while (fabs(b - a) >= error_tolerance); if (fabs(f(c)) < error_tolerance) { return 0;
printf("Root: c = %.6lf\n", c); break; }
printf("f(c) = %.6lf\n", f(c)); return 0; }
}
if (f(c) * f(a) < 0) {
b = c;
} else {
a = c;
}
} while (fabs(b - a) >= error_tolerance);
printf("Root: c = %.6lf\n", c);
printf("f(c) = %.6lf\n", f(c));
return 0;
}
return 0;
}