fork download
  1. function [ root, iteration_info ] = bisection( f, a, b, eps )
  2. % Arguments:
  3. % [a, b] - interval, a < b
  4. % f - continuous function defined on [a, b], f(a) and f(b) have opposite signs
  5. % eps - max error
  6. % Returns:
  7. % root - found root
  8. % iteration_info - matrix of size (number_of_iterations)x5; row layout: [iteration, a, c, b, c - a]
  9.  
  10. iteration = 0;
  11. iteration_info = [];
  12. while true
  13. iteration = iteration + 1;
  14. c = (a + b) / 2;
  15. iteration_info(iteration, :) = [iteration, a, c , b, c - a];
  16.  
  17. if c - a <= eps
  18. break
  19. end
  20.  
  21. if f(a) * f(c) < 0
  22. b = c;
  23. else
  24. a = c;
  25. end
  26. end
  27. root = c;
  28. end
  29.  
  30. format short g
  31. [result, info] = bisection(@(x)(x+log(2*x)), 0.2, 0.75, 0.00005)
Success #stdin #stdout 0.27s 411840KB
stdin
Standard input is empty
stdout
result =    0.35177
info =

           1         0.2       0.475        0.75       0.275
           2         0.2      0.3375       0.475      0.1375
           3      0.3375     0.40625       0.475     0.06875
           4      0.3375     0.37188     0.40625    0.034375
           5      0.3375     0.35469     0.37188    0.017188
           6      0.3375     0.34609     0.35469   0.0085938
           7     0.34609     0.35039     0.35469   0.0042969
           8     0.35039     0.35254     0.35469   0.0021484
           9     0.35039     0.35146     0.35254   0.0010742
          10     0.35146       0.352     0.35254  0.00053711
          11     0.35146     0.35173       0.352  0.00026855
          12     0.35173     0.35187       0.352  0.00013428
          13     0.35173      0.3518     0.35187  6.7139e-05
          14     0.35173     0.35177      0.3518  3.3569e-05