Skip to content

Instantly share code, notes, and snippets.

@nicoguaro
Created February 11, 2026 13:49
Show Gist options
  • Select an option

  • Save nicoguaro/0807da1658f452f12038e6f7a67d6332 to your computer and use it in GitHub Desktop.

Select an option

Save nicoguaro/0807da1658f452f12038e6f7a67d6332 to your computer and use it in GitHub Desktop.
Complex step differentiation evaluation for step size.
# -*- coding: utf-8 -*-
"""
Comparison of error in the derivative approximation as
a function of step size for different methods.
@author: Nicolás Guarín-Zapata
@date: February 2026
"""
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["mathtext.fontset"] = "cm"
def D_p(x, h, fun):
return (fun(x + h) - fun(x))/h
def D_m(x, h, fun):
return (fun(x) - fun(x - h))/h
def D_0(x, h, fun):
return (fun(x + h) - fun(x - h))/(2*h)
def D_complex(x, h, fun):
return np.imag(fun(x + 1j*h))/h
#%%
h = np.logspace(-1, -8, 10)
x0 = 1.0
fun = lambda x: np.sin(np.asarray(x))
grad = lambda x: np.cos(np.asarray(x))
pendiente_ex = grad(x0)
pendiente_p = D_p(x0, h, fun)
pendiente_m = D_m(x0, h, fun)
pendiente_0 = D_0(x0, h, fun)
pendiente_complex = D_complex(x0, h, fun)
error_p = pendiente_ex - pendiente_p
error_m = pendiente_ex - pendiente_m
error_0 = pendiente_ex - pendiente_0
error_complex = pendiente_ex - pendiente_complex
plt.figure(figsize=(5, 4))
plt.loglog(h, np.abs(np.cos(x0) - pendiente_p), lw=2, marker="o")
plt.loglog(h, np.abs(np.cos(x0) - pendiente_m), linestyle="--")
plt.loglog(h, np.abs(np.cos(x0) - pendiente_0), marker="s")
plt.loglog(h, np.abs(np.cos(x0) - pendiente_complex), marker="^")
plt.xlabel("$h$")
plt.ylabel("$|E(h)|$")
plt.legend(["$D_p$", "$D_m$", "$D_0$", "$D_{\mathbb{C}}$"])
plt.tight_layout()
plt.savefig("complex_differentiation.png", dpi=600)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment