2nd_Sem_Bogachev/2025.05.02/dist/Ulyanov_MT/task01.c
2025-05-02 01:18:28 +03:00

77 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "io_status.h"
#include "functions.h"
#include "comparison.h"
int solve1(double, double, double, int, double*, double (*)(double));
int main(int argc, char* argv[])
{
int task = 1;
double a, b, eps;
int maxit, k;
double t;
double (*f)(double);
double (*func[])(double) = {f0, f1, f2, f3, f4, f5, f6};
double x = 0, fx;
int it, c;
if (!(argc == 6 && sscanf(argv[1], "%lf", &a) == 1 && sscanf(argv[2], "%lf", &b) == 1 && sscanf(argv[3], "%le", &eps) == 1 && sscanf(argv[4], "%d", &maxit) == 1 && sscanf(argv[5], "%d", &k) == 1 && k >= 0 && k <= 6))
{
printf("Usage: %s a b eps M k\n", argv[0]);
return -1;
}
f = func[k];
t = clock();
it = solve1(a, b, eps, maxit, &x, f);
t = (clock() - t) / CLOCKS_PER_SEC;
c = get_count();
if (it < 0)
{
printf("%s : Task = %d NOT FOUND Count = %d T = %.2f\n", argv[0], task, c, t);
return -1;
}
fx = (*f)(x);
printf("%s : Task = %d X = %e Res = %e Its = %d Count = %d T = %.2f\n", argv[0], task, x, fx, it, c, t);
return 0;
}
int solve1(double a, double b, double eps, int maxit, double* x, double (*f)(double))
{
int it;
double fa = (*f)(a), fb = (*f)(b);
double c = 0, fc = 0;
if (fabs(fa) < eps) {*x = a; return 0;}
if (fabs(fb) < eps) {*x = b; return 0;}
for (it = 0; it < maxit; it++)
{
c = (a + b) / 2;
if ((c >= a) && (c <= a)) {*x = b; break;}
if ((c >= b) && (c <= b)) {*x = a; break;}
fc = (*f)(c);
if (fa * fc <= 0)
{
b = c;
fb = fc;
}
if (fb * fc <= 0)
{
a = c;
fa = fc;
}
if (fabs(b - a) < eps)
{
*x = a;
break;
}
}
if ((a >= b) && (a <= b))
{
*x = a;
return it;
}
if (it >= maxit) return -1;
return it;
}