Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. >> my_fun = @(x) 5*x^4 - 2.7*x^2 - 2*x + .5;
  2. low = .1;
  3. high = 0.5;
  4. tolerance = .00001;
  5. x = bisection(my_fun, low, high, tolerance);
  6. Bisection Method
  7. Iter low high x0
  8. 0 0.100000 0.500000 0.300000
  9. Root at x = 0.200000
  10.  
  11.  
  12.  
  13.  
  14. CODE
  15.  
  16.  
  17. function m = bisection(f, low, high, tol, maxit)
  18. disp('Bisection Method');
  19.  
  20. % Evaluate both ends of the interval
  21. j = maxit;
  22. y1 = feval(f, low);
  23. y2 = feval(f, high);
  24. i = 0;
  25.  
  26. % Display error and finish if signs are not different
  27. if y1 * y2 > 0
  28. disp('Have not found a change in sign. Will not continue...');
  29. m = 'Error'
  30. return
  31. end
  32.  
  33. % Work with the limits modifying them until you find
  34. % a function close enough to zero.
  35. disp('Iter low high x0');
  36. while (abs(high - low) >= tol) && (maxit<j)
  37.  
  38.  
  39.  
  40.  
  41. j = j + 1;
  42. i = i + 1;
  43. % Find a new value to be tested as a root
  44. m = (high + low)/2;
  45. y3 = feval(f, m);
  46. if y3 == 0
  47. fprintf('Root at x = %f \n\n', m);
  48. return
  49. end
  50. fprintf('%2i \t %f \t %f \t %f \n', i-1, low, high, m);
  51.  
  52. % Update the limits
  53. if y1 * y3 > 0
  54. low = m;
  55. y1 = y3;
  56. else
  57. high = m;
  58. end
  59. end
  60.  
  61.  
  62.  
  63. % Show the last approximation considering the tolerance
  64. w = feval(f, m);
  65. fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, y3, i-1);
  66. fprintf(' Approximation with tolerance = %f \n', tol);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement