Don't like ads? PRO users don't see any ads ;-)
Guest

bisect.c

By: a guest on Aug 10th, 2012  |  syntax: C  |  size: 0.79 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // c program for implementation of bisection -- abhay's version
  2. #include<stdio.h>
  3.  
  4. float fun(float);
  5.  
  6. main()
  7. {
  8.     float x1, x2, r;
  9.     int i, j;
  10.     for(i=0; i<10; i++)
  11.     {
  12.         printf("i = %d, fun(i) = %f\n", i, fun(i));
  13.         if(fun(i) < 0)
  14.             break;
  15.     }
  16.     printf("\n i = %d\n", i);
  17.  
  18.     x1 = i;
  19.  
  20.     printf("x1 = %f\n", x1);
  21.  
  22.     for(j=0; j<10; j++)
  23.     {
  24.         if(fun(j) > 0)
  25.             break;
  26.     }
  27.  
  28.     x2 = j;
  29.     printf("x2 = %d", x2);
  30.  
  31.     while(1)
  32.     {
  33.         r = (x1 + x2)/2;
  34.         if( fun(r) < 0)
  35.             x1 = r;
  36.         else x2 = r;
  37.  
  38.         if( abs(fun(x2) - fun(x1) <= 0.0001))
  39.             break;
  40.     }
  41.  
  42.     printf("\nYour root is : %f", r);
  43.  
  44.     return 0;
  45. }
  46.  
  47. float fun(float x)
  48. {
  49.     return (x*x) - (4*x) + 1;
  50. }