fork(1) download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double f(double x) {
  5. return x * x - 1.0 - sin(x);
  6. }
  7.  
  8. void bisection(double xl, double xr) {
  9. double xi;
  10. int count = 0;
  11. while (1) {
  12. xi = (xl + xr) / 2.0;
  13. count++;
  14. if (fabs(f(xi)) < 1e-5) break;
  15.  
  16. if (f(xl) * f(xi) < 0) xr = xi;
  17. else xl = xi;
  18. }
  19. printf("Bisection: x = %f (Iterations: %d)\n", xi, count);
  20. }
  21.  
  22. void falsePosition(double xl, double xr) {
  23. double xi;
  24. int count = 0;
  25. while (1) {
  26. // Linear interpolation formula
  27. xi = (xl * f(xr) - xr * f(xl)) / (f(xr) - f(xl));
  28. count++;
  29. if (fabs(f(xi)) < 1e-5) break;
  30.  
  31. if (f(xl) * f(xi) < 0) xr = xi;
  32. else xl = xi;
  33. }
  34. printf("False Position: x = %f (Iterations: %d)\n", xi, count);
  35. }
  36.  
  37. int main() {
  38. // Root 1 interval approx [-1, 0]
  39. // Root 2 interval approx [1, 2]
  40. printf("Finding root in [1, 2]:\n");
  41. bisection(1.0, 2.0);
  42. falsePosition(1.0, 2.0);
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Finding root in [1, 2]:
Bisection: x = 1.409622 (Iterations: 16)
False Position: x = 1.409622 (Iterations: 9)