Matlab导数定义一致性验证程序及函数句柄使用咨询
Fixing Your Derivative Consistency Check in MATLAB
Hey there! Let's get your code working correctly and clear up those questions about function handles.
First: Your Function Handle Syntax
Your f=@(x)sin(x) is perfectly correct for an anonymous function handle. The only tiny mistake is with your derivative handle: you wrote df=@(x)cosx but it should be df=@(x)cos(x) (don't forget the parentheses after cos). That's an easy fix!
Issues in Your Original Function
The main problem with your current code is that errList gets overwritten every loop iteration—by the end, it will only hold the last error value, not the full list of errors as h shrinks. We need to initialize it as an array first.
Here's the revised, working version of your function with comments explaining each change:
function [errList] = diffConsistency(f, df, x, iMax, h0) % Initialize errList as an array to store all errors errList = zeros(1, iMax); h = h0; for i = 1:iMax % Compute the finite difference approximation leftSide = (f(x + h) - f(x)) / h; % Compute the exact derivative rightSide = df(x); % Store the absolute error for this h errList(i) = abs(leftSide - rightSide); % Shrink h by a factor of 10 for the next iteration h = h * 1e-1; end end
How to Call the Function
Let's test it with your sin(x) and cos(x) example. Pick a test point (like x = pi/4, where we know sin(pi/4)=cos(pi/4)=sqrt(2)/2) and run this code:
% Define function and its exact derivative f = @(x) sin(x); df = @(x) cos(x); % Set parameters x = pi/4; % Test point iMax = 10; % Number of h values to test h0 = 1; % Initial step size % Call the function errorList = diffConsistency(f, df, x, iMax, h0); % Display the results disp('Step size h | Absolute Error'); disp('-----------------------------'); h_values = h0 .* (1e-1).^(0:iMax-1); for k = 1:iMax fprintf('%.1e | %.12f\n', h_values(k), errorList(k)); end % Optional: Plot error vs h (log-log scale to see the trend) figure; loglog(h_values, errorList, '-o'); xlabel('Step Size h'); ylabel('Absolute Error'); title('Finite Difference Error vs Step Size'); grid on;
What You'll Observe
- At first, as
hgets smaller, the error will decrease (since the finite difference gets closer to the exact derivative). - But once
his extremely small (around1e-8or smaller in MATLAB), the error will start to increase again. This is due to floating-point precision limits: whenx+his almost identical tox, subtracting them loses significant digits ("catastrophic cancellation").
That's all you need to get your consistency check working properly!
内容的提问来源于stack exchange,提问作者p.late

