Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <string.h>
  5. #define EPS 1e-15
  6.  
  7. //prototypes
  8. double f(double);
  9. void solve(double (*f)(double), double, double);
  10. double root(double (*f)(double), double, double);
  11. //----------
  12.  
  13. double f(double x) { return (x*x-9)*(x-1)*sin(x)/(x*x*x+2*x*x+9); }
  14.  
  15. int main(void)
  16. {
  17.     double l = -4, r = 4; //границы корней
  18.     solve(f,l,r);
  19.     return 0;
  20. }
  21.  
  22. void solve(double (*f)(double x), double l, double r)
  23. {
  24.     const int n = 1e+8 + 3; int i;
  25.     double h = (r-l)/n, x1 = l, x2;
  26.     for  (i=0;i<n;i++)
  27.     {
  28.         x2 = l + i*h;
  29.         if (f(x1)*f(x2)<0)
  30.             printf("root = %.10f\n",root(f,x1,x2));
  31.         x1 = x2;
  32.     }
  33. }
  34.  
  35. double root(double (*f)(double x), double a, double b)
  36. {
  37.     double c, fa = f(a), fb = f(b), fc;
  38.     if (fabs(fa)<EPS)
  39.         return a;
  40.     if (fabs(fb)<EPS)
  41.         return b;
  42.     while (b-a>EPS)
  43.     {
  44.         c = (a+b)/2;
  45.         fc = f(c);
  46.         if (fa*fc < 0)
  47.             b = c;
  48.         else
  49.             a = c;
  50.     }
  51.     return (a+b)/2;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement