fork download
  1. % f(x) = x^3 − 9x^2 + 3.8197
  2. % f'(x) = 3x^2 − 18x
  3.  
  4. % Define functions
  5. func = @(x) x.^3 - 9*x.^2 + 3.8197;
  6. diff_func = @(x) 3*x.^2 - 18*x;
  7.  
  8. % Random initial guess
  9. x = rand();
  10. fprintf('x_0 = %.4f\n', x);
  11.  
  12. % Table header
  13. fprintf('%-3s %-12s %-12s %-12s %-12s\n', ...
  14. 'n','x_i','f(x)','f''(x)','|x_(i+1)-x_i|');
  15.  
  16. % Newton iterations
  17. for count = 1:5
  18. fx = func(x);
  19. dfx = diff_func(x);
  20. next_x = x - fx/dfx;
  21. fprintf('%-3d %-12.6f %-12.6f %-12.6f %-12.6f\n', ...
  22. count, x, fx, dfx, abs(next_x-x));
  23. x = next_x;
  24. end
  25.  
Success #stdin #stdout 0.19s 46788KB
stdin
Standard input is empty
stdout
x_0 = 0.5214
n   x_i          f(x)         f'(x)        |x_(i+1)-x_i|
1   0.521373     1.514958     -8.569222    0.176791    
2   0.698163     -0.226882    -11.104645   0.020431    
3   0.677732     -0.002891    -10.821216   0.000267    
4   0.677465     -0.000000    -10.817493   0.000000    
5   0.677465     -0.000000    -10.817492   0.000000