MATLAB/PYTHON: Parts (d) and (e) only Please show all the steps as much as possible Be sure to follow the instructions Matlab code: function root = find_root_trisection(f, a, b, tol, max_iter) if f(a) * f(b) > 0 error('The function does not change sign in the given interval [a, b].'); end for i = 1:max_iter dx = (b - a) / 3; x1 = a + dx; x2 = b - dx; if abs(f(x1)) < tol root = x1; return; end if abs(f(x2)) < tol root = x2; return; end if f(x1) * f(a) < 0 b = x1; else a = x1; end if f(x2) * f(b) < 0 a = x2; end end error('Failed to converge to a root after %d iterations.', max_iter); end --------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- Python code: def find_root_trisection(f, a, b, tol=1e-6, max_iter=100): if f(a) * f(b) > 0: raise ValueError("The function does not change sign in the given interval [a, b].") for i in range(max_iter): dx = (b - a) / 3 x1 = a + dx x2 = b - dx if abs(f(x1)) < tol: return x1 if abs(f(x2)) < tol: return x2 if f(x1) * f(a) < 0: b = x1 else: a = x1 if f(x2) * f(b) < 0: a = x2 raise Exception(f"Failed to converge to a root after {max_iter} iterations.")
MATLAB/PYTHON:
- Parts (d) and (e) only
- Please show all the steps as much as possible
- Be sure to follow the instructions
Matlab code:
function root = find_root_trisection(f, a, b, tol, max_iter)
if f(a) * f(b) > 0
error('The function does not change sign in the given interval [a, b].');
end
for i = 1:max_iter
dx = (b - a) / 3;
x1 = a + dx;
x2 = b - dx;
if abs(f(x1)) < tol
root = x1;
return;
end
if abs(f(x2)) < tol
root = x2;
return;
end
if f(x1) * f(a) < 0
b = x1;
else
a = x1;
end
if f(x2) * f(b) < 0
a = x2;
end
end
error('Failed to converge to a root after %d iterations.', max_iter);
end
---------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
Python code:
def find_root_trisection(f, a, b, tol=1e-6, max_iter=100):
if f(a) * f(b) > 0:
raise ValueError("The function does not change sign in the given interval [a, b].")
for i in range(max_iter):
dx = (b - a) / 3
x1 = a + dx
x2 = b - dx
if abs(f(x1)) < tol:
return x1
if abs(f(x2)) < tol:
return x2
if f(x1) * f(a) < 0:
b = x1
else:
a = x1
if f(x2) * f(b) < 0:
a = x2
raise Exception(f"Failed to converge to a root after {max_iter} iterations.")
Step by step
Solved in 5 steps with 2 images