fork download
  1. f = @(x) x^2 - 2; % Function definition
  2.  
  3. a = 2;
  4. b = 3;
  5.  
  6. for i = 1:8
  7. r = (a + b) / 2; % Midpoint calculation
  8. disp(['Iteration ', num2str(i), ' : r = ', num2str(r)]);
  9.  
  10. if f(a) * f(r) < 0
  11. b = r; % Root lies in [a, r]
  12. else
  13. a = r; % Root lies in [r, b]
  14. end
  15.  
  16. err(i) = abs(b - a);
  17. disp(['Error = ', num2str(err(i))]);
  18. end
  19.  
  20. fprintf('\nFinal root estimate after 8 iterations: %.10f\n', r);
  21. # your code goes here
Success #stdin #stdout 0.16s 47388KB
stdin
Standard input is empty
stdout
Iteration 1 : r = 2.5
Error = 0.5
Iteration 2 : r = 2.75
Error = 0.25
Iteration 3 : r = 2.875
Error = 0.125
Iteration 4 : r = 2.9375
Error = 0.0625
Iteration 5 : r = 2.9688
Error = 0.03125
Iteration 6 : r = 2.9844
Error = 0.015625
Iteration 7 : r = 2.9922
Error = 0.0078125
Iteration 8 : r = 2.9961
Error = 0.0039062

Final root estimate after 8 iterations: 2.9960937500