Advertisement
wojtas626

[C] JiMP 11.4

Jan 12th, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. double f1(double x)
  6. {
  7.     return (2*x);
  8. }
  9.  
  10. double f2(double x)
  11. {
  12.     return (x*x - 5*x + 4);
  13. }
  14.  
  15. double f3(double x)
  16. {
  17.     return (3*x*x*x - 5*x - 1);
  18. }
  19.  
  20. double bisection(double (*f)(), double floor, double ceiling, double approximation)
  21. {
  22.     while(abs(f((ceiling + floor)/2)) >= approximation)
  23.     {
  24.         double x = (floor + ceiling) / 2;
  25.         if (f(floor) * f(x) <= 0)
  26.         {
  27.             ceiling = x;
  28.         }
  29.         else if ( f(ceiling) * f(x) <= 0 )
  30.         {
  31.             floor = x;
  32.         }
  33.     }
  34.     return ((floor + ceiling)/2);
  35. }
  36.  
  37. void menu()
  38. {
  39.     double floor, ceiling;
  40.     int choice;
  41.  
  42.     printf("1. f(x) = 2x\n2. f(x) = x^2 - 5x + 4\n3. f(x) = 3x^2 - 5x - 1\n");
  43.     scanf("%i", &choice);
  44.     printf("\n");
  45.     printf("Podaj dolna granice przedzialu: ");
  46.     scanf("%lf", &floor);
  47.     printf("\n");
  48.     printf("Podaj gorna granice przedzialu: ");
  49.     scanf("%lf", &ceiling);
  50.  
  51.     switch (choice)
  52.     {
  53.     case 1:
  54.         printf("%lf", bisection(&f1, floor, ceiling, 1.e-5));
  55.         break;
  56.     case 2:
  57.         printf("%lf", bisection(&f2, floor, ceiling, 1.e-5));
  58.         break;
  59.     case 3:
  60.         printf("%lf", bisection(&f3, floor, ceiling, 1.e-5));
  61.         break;
  62.     }
  63. }
  64.  
  65. int main()
  66. {
  67.     menu();
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement