lab.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<math.h>
  4. double poly(double x) {
  5. return 0.25 * pow(x,3) + x - 1.2502;
  6. }
  7. double alg(double x) {
  8. return pow(x,4) + 3 * pow(x,3) - 9 * x - 9;
  9. }
  10. double algbrake(double x) {
  11. return -(pow(x,4) + 3 * pow(x,3) - 9 * x - 9)/(x-1.5);
  12. }
  13. double secant(double(*f)(double), double xk, double xk1, double eps, int N) {
  14. double xk2;
  15. double fxk = f(xk);
  16. double fxk1 = f(xk1);
  17. for (int i = 1; i < N; i++)
  18. {
  19. if (fabs(xk1 - xk) < eps) {
  20. break;
  21. }
  22. xk2 = xk1 - fxk1 * ((xk1 - xk) / (fxk1 - fxk));
  23. xk = xk1;
  24. fxk = fxk1;
  25. xk1 = xk2;
  26. fxk1 = f(xk2);
  27. }
  28. return xk2;
  29. }
  30. double bisection(double(*f)(double), double a, double b, double eps, int N) {
  31. double fa = f(a);
  32. double fb = f(b);
  33. double c;
  34. if (fa * fb >= 0) {
  35. return 0;
  36. }
  37. for (int i = 0; i < N; i ++)
  38. {
  39. c = 0.5 * (a + b);
  40. if ((b - a) < 2*eps) {
  41. return c;
  42. }
  43. double fc = f(c);
  44. if (fa * fc > 0) {
  45. a = c;
  46. fa = fc;
  47. }
  48. else {
  49. b = c;
  50. fb = fc;
  51. }
  52. }
  53. return c;
  54. }
  55. void PrintResult (double eps) {
  56. double x1 = secant(algbrake, 1.51, 2, eps, 1000);
  57. double x2 = bisection(algbrake, 1.51, 2, eps, 1000);
  58. printf("Function with a brake: \n");
  59. printf("Secant method: \n");
  60. printf("x = %lf\n", x1);
  61. printf("Bisection method: \n");
  62. printf("x = %lf\n", x2);
  63. double x3 = secant(alg, 1, 2, eps, 1000);
  64. double x4 = bisection(alg, 1, 2, eps, 1000);
  65. printf("Algebraic function: \n");
  66. printf("Secant method: \n");
  67. printf("x = %lf\n", x3);
  68. printf("Bisection method: \n");
  69. printf("x = %lf\n", x4);
  70. double x5 = secant(poly, 0, 2, eps, 1000);
  71. double x6 = bisection(poly, 0, 2, eps, 1000);
  72. printf("Polynomial: \n");
  73. printf("Secant method: \n");
  74. printf("x = %lf\n", x5);
  75. printf("Bisection method: \n");
  76. printf("x = %lf\n", x6);
  77. }
  78. int main() {
  79. PrintResult(pow(10, -5));
  80. }