I am trying to compute the divergence of a vector field:
Fx = np.cos(xx + 2*yy)
Fy = np.sin(xx - 2*yy)
F = np.array([Fx, Fy])
Analytic Solution
This is how the divergence (div(F) = dF/dx + dF/dy ) should look like, based on the analytic computation of the divergence (see Wolfram Alpha here):
- dFx/dx = d/dx cos(x+2y) = -sin(x+2y)
- dFy/dy = d/dy sin(x-2y) = -2*cos(x-2y)
The divergence:
div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)
The code:
import numpy as np
import matplotlib.pyplot as plt
# Number of points (NxN)
N = 50
# Boundaries
ymin = -2.; ymax = 2.
xmin = -2.; xmax = 2.
# Create Meshgrid
x = np.linspace(xmin,xmax, N)
y = np.linspace(ymin,ymax, N)
xx, yy = np.meshgrid(x, y)
# Analytic computation of the divergence (EXACT)
div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)
# PLOT
plt.imshow(div_analy , extent=[xmin,xmax,ymin,ymax], origin="lower", cmap="jet")
Numeric Solution
Now, I am trying to obtain the same numerically, so I used this function to compute the divergence
def divergence(f,sp):
""" Computes divergence of vector field
f: array -> vector field components [Fx,Fy,Fz,...]
sp: array -> spacing between points in respecitve directions [spx, spy,spz,...]
"""
num_dims = len(f)
return np.ufunc.reduce(np.add, [np.gradient(f[i], sp[i], axis=i) for i in range(num_dims)])
When I plot the divergence using this function:
# Compute Divergence
points = [x,y]
sp = [np.diff(p)[0] for p in points]
div_num = divergence(F, sp)
# PLOT
plt.imshow(div_num, extent=[xmin,xmax,ymin,ymax], origin="lower", cmap="jet")
... I get:
The issue
The numeric solution is different from the analytic solution! What am I doing wrong?