123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- #include<stdio.h>
- #include<stdlib.h>
- #include<math.h>
- double poly(double x) {
- return 0.25 * pow(x,3) + x - 1.2502;
- }
- double alg(double x) {
- return pow(x,4) + 3 * pow(x,3) - 9 * x - 9;
- }
- double algbrake(double x) {
- return -(pow(x,4) + 3 * pow(x,3) - 9 * x - 9)/(x-1.5);
- }
- double secant(double(*f)(double), double xk, double xk1, double eps, int N) {
- double xk2;
- double fxk = f(xk);
- double fxk1 = f(xk1);
- for (int i = 1; i < N; i++)
- {
- if (fabs(xk1 - xk) < eps) {
- break;
- }
- xk2 = xk1 - fxk1 * ((xk1 - xk) / (fxk1 - fxk));
- xk = xk1;
- fxk = fxk1;
- xk1 = xk2;
- fxk1 = f(xk2);
- }
- return xk2;
- }
- double bisection(double(*f)(double), double a, double b, double eps, int N) {
- double fa = f(a);
- double fb = f(b);
- double c;
- if (fa * fb >= 0) {
- return 0;
- }
- for (int i = 0; i < N; i ++)
- {
- c = 0.5 * (a + b);
-
- if ((b - a) < 2*eps) {
- return c;
- }
- double fc = f(c);
- if (fa * fc > 0) {
- a = c;
- fa = fc;
- }
- else {
- b = c;
- fb = fc;
- }
- }
- return c;
- }
- void PrintResult (double eps) {
- double x1 = secant(algbrake, 1.51, 2, eps, 1000);
- double x2 = bisection(algbrake, 1.51, 2, eps, 1000);
- printf("Function with a brake: \n");
- printf("Secant method: \n");
- printf("x = %lf\n", x1);
- printf("Bisection method: \n");
- printf("x = %lf\n", x2);
-
- double x3 = secant(alg, 1, 2, eps, 1000);
- double x4 = bisection(alg, 1, 2, eps, 1000);
- printf("Algebraic function: \n");
- printf("Secant method: \n");
- printf("x = %lf\n", x3);
- printf("Bisection method: \n");
- printf("x = %lf\n", x4);
- double x5 = secant(poly, 0, 2, eps, 1000);
- double x6 = bisection(poly, 0, 2, eps, 1000);
- printf("Polynomial: \n");
- printf("Secant method: \n");
- printf("x = %lf\n", x5);
- printf("Bisection method: \n");
- printf("x = %lf\n", x6);
- }
- int main() {
- PrintResult(pow(10, -5));
- }
|