function handles and anonymous functions
显示 更早的评论
hello everyone,
I have a problem doing the following question.
Write a function xb=bisection(f, a, b, tol) and a function xn=newton(f,x0,tol) which both ?nd a zero of f(x) in the interval [a,b], using the bisection and newton algorithms. For the newton function, use the function deriv from problem (2) of this assignment to compute the derivative of the function at each iteration. Then, ?nd the zero of the following functions near the given points: f(x) = cos(x 2) + sin(2x) near x = 2 g(x) = x-5ln(x) near x = 1 Also, display the number of iterations each method takes to ?nd the zero. In writing the driver routine that calls bisection and newton. This is what i did, but its not returning anything. The code is not doing anything, plus its not printing the iteration number of each method
This is the bisection part
function x = bisection(f,a,b,tol)
x =( b-a)/2;
left = a;
right=b;
i =0;
while abs(f(x))>tol
sign = f(x)/abs(x);
signleft= f(left)/abs(f(left));
if signleft <0 && sign >0
right= x;
else
left =x;
end
x =(right-left)/2;
i = i+1;
end
fprintf('bisection Iteration =%i\n',i)
This is newton part
function xn = newton(f,x0,tol)
xn = x0;
i= 0;
while abs(f(xn)) > tol
xn = xn - f(xn)/deriv(f,xn,tol);
i=i+1;
end
fprintf('newton Iteration =%i\n',i)
This is test root part
f = @(x)(cos(x/2)+sin(2*x));
g = @(x)(x-5*ln(x));
tol = 10 *exp(-6);
y= bisection(f,1,4,tol);
x= bisection (g,0,1.5,tol);
h = newton(f,2,tol);
k= newton(g,1,tol);
fprintf('%f %f\n',y,x)
fprintf('%f %f\n',h,k)
**
This is the deriv function
function D= deriv(f,a,h)
D = (f(a+h) -f(a-h))/2*h;
end
**
1 个评论
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!