Skip to content

Instantly share code, notes, and snippets.

@higham
Last active November 2, 2021 15:45
Show Gist options
  • Save higham/6668082d7d51442474f11ae96130d2db to your computer and use it in GitHub Desktop.
Save higham/6668082d7d51442474f11ae96130d2db to your computer and use it in GitHub Desktop.
Complex step example
% Complex step example. Requires Symbolic Math Toolbox.
format long
syms x; f = atan(x)/(1+exp(-x^2))
% Derivative at $a = 2$:
a = 2; fd = double(subs( diff(f), a))
% Convert symbolic function to MATLAB function.
f = matlabFunction(f);
% Complex step approximation is
fd_cs = complex_step(f,a)
% Finite difference approximations with step $u$ and $u^{1/2}$:
u = 4*eps;
fd_fd1 = (f(a+u)-f(a))/u
fd_fd2 = (f(a+u^(1/2))-f(a))/u^(1/2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment