t1nman

Math.lab3

May 19th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #define F(x) (x)*(x)*(x)*(x)*(x) - 3*(x)*(x) + 1
  4. #define f(x) 5*(x)*(x)*(x)*(x) - 6*(x)
  5. #define f_2(x) 20*(x)*(x)*(x) - 6
  6. #define EPS_BIN 0.1
  7. #define EPS 0.0005
  8.  
  9. float half_division(float, float);
  10. float newton(float);
  11. void kantorovich(float);
  12.  
  13. int main()
  14. {
  15.     float a0 = half_division(-1.0, 0.0);
  16.     float a1 = half_division(0.0, 1.0);
  17.     float a2 = half_division(1.0, 2.0);
  18.  
  19.     printf("\nRoots approximations (eps = 0.1):\n");
  20.     printf("\tx1 = %f\tF(x1) = %f\n", a0, F(a0));
  21.     kantorovich(a0);
  22.     printf("\tx2 = %f\tF(x2) = %f\n", a1, F(a1));
  23.     kantorovich(a1);
  24.     printf("\tx3 = %f\tF(x3) = %f\n", a2, F(a2));
  25.     kantorovich(a2);
  26.     putchar('\n');
  27.  
  28.     float x1 = newton(a0);
  29.     float x2 = newton(a1);
  30.     float x3 = newton(a2);
  31.     printf("Roots approximations (eps = 0.0005):\n");
  32.     printf("\tx1 = %f\tF(x1) = %f\n\n", x1, F(x1));
  33.     printf("\tx2 = %f\tF(x2) = %f\n\n", x2, F(x2));
  34.     printf("\tx3 = %f\tF(x3) = %f\n\n", x3, F(x3));
  35.  
  36.     return 0;
  37. }
  38.  
  39. void kantorovich(float x0)
  40. {
  41.     float fx0 = f(x0);
  42.     float B = fabs(1/fx0);
  43.     float Fx0 = F(x0);
  44.     float nu = fabs(Fx0/fx0);
  45.     float f_2 = f_2(x0);
  46.     float K = fabs(f_2);
  47.     float h = B * nu * K;
  48.     float a = (1 - sqrt(1 - 2*h)) / h * nu;
  49.     if ((h < 0.5) && (a < 0.5))
  50.         printf("\th = %f < 0.5\ta(h) = %f < 0.5\n\n\n", h, a);
  51. }
  52.  
  53. float newton(float x0)
  54. {
  55.     float fx0 = f(x0);
  56.     float Fx0 = F(x0);
  57.     float x1 = x0 - Fx0 / fx0;
  58.  
  59.     while (fabs(x0 - x1) >= EPS) {
  60.         x0 = x1;
  61.         Fx0 = F(x0);
  62.         x1 = x0 - Fx0 / fx0;
  63.     }
  64.    
  65.     return x1;
  66. }
  67.  
  68. float half_division(float a, float b)
  69. {
  70.     float left = a, right = b;
  71.     float middle = left + (right-left)/2.0;
  72.    
  73.     while ((right-left) > EPS_BIN/2.0){
  74.         if (F(middle) < 0) {
  75.             if (F(left) > 0)
  76.                 right = middle;
  77.             else
  78.                 left = middle;
  79.         } else {
  80.             if (F(left) < 0)
  81.                 right = middle;
  82.             else
  83.                 left = middle;
  84.         }
  85.         middle = left + (right-left)/2.0;
  86.     }
  87.  
  88.     return middle;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment