在 Python 中正确计算向量场的散度

hen*_*nry 10 python math numpy matplotlib

我正在尝试计算向量场的散度:

Fx  = np.cos(xx + 2*yy)
Fy  = np.sin(xx - 2*yy)
F = np.array([Fx, Fy])
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

分析解决方案

这是基于散度的解析计算的散度 (div(F) = dF/dx + dF/dy ) 的样子(请参阅此处的Wolfram Alpha ):

  • dFx/dx = d/dx cos(x+2y) = -sin(x+2y)
  • dFy/dy = d/dy sin(x-2y) = -2*cos(x-2y)

分歧:

div_analy = -np.sin(xx + 2*yy) - 2*np.cos(xx - 2*yy)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

编码:

# 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")
Run Code Online (Sandbox Code Playgroud)

数值解

现在,我试图获得相同的数值,所以我使用这个函数来计算散度

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)])
Run Code Online (Sandbox Code Playgroud)

当我使用此函数绘制散度图时:

 # 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")
Run Code Online (Sandbox Code Playgroud)

......我明白了:

在此处输入图片说明

问题

数值解不同于解析解!我究竟做错了什么?

小智 2

这两张图都是错误的,因为你用np.meshgrid错了方法。

代码的其他部分需要xx[a, b], yy[a, b] == x[a], y[b],其中 a, b 是您的情况下 0 到 49 之间的整数。

另一方面,你写

xx, yy = np.meshgrid(x, y)
Run Code Online (Sandbox Code Playgroud)

什么导致xx[a, b], yy[a, b] == x[b], y[a]。此外, 的值div_analy[a, b]变成了-sin(x[b]+2y[a]) - 2cos(x[b]+2y[a]),并且 的值div_num[a, b]也变成了其他一些错误的值。

你可以简单地通过写来修复它

yy, xx = np.meshgrid(x, y)
Run Code Online (Sandbox Code Playgroud)

然后你会看到两种解决方案都得到了正确的结果。

顺便说一句,您设置了N = 50,这样np.linspace(xmin,xmax, N)间隔中需要 50 个点[-2, 2],并且相邻点之间的距离将为 1/49。设置N=51可以获得更可靠的线路空间。