求出某空间曲面下的体积
flyfish
用小长方体的体积和来逼近该体积
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 定义函数 f(x, y)
def f(x, y):
return np.sin(np.pi * x) * np.sin(np.pi * y)
# 创建网格
x = np.linspace(0, 1, 30)
y = np.linspace(0, 1, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
# 创建绘图对象
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Volume under the surface $f(x, y) = \sin(\pi x) \sin(\pi y)$')
# 更新函数,用于动画
def update(num):
ax.clear()
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Volume under the surface $f(x, y) = \sin(\pi x) \sin(\pi y)$')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.5, cmap='viridis', edgecolor='none')
# 显示小长方体
if num > 0:
for i in range(0, num):
for j in range(0, num):
dx = dy = 1 / num
dz = f((i+0.5)/num, (j+0.5)/num)
x_pos = i / num
y_pos = j / num
ax.bar3d(x_pos, y_pos, 0, dx, dy, dz, alpha=0.3, color='b', edgecolor='k')
# 创建动画
ani = animation.FuncAnimation(fig, update, frames=30, repeat=True)
# 保存为 GIF
ani.save('multivariable_calculus_animation.gif', writer='imagemagick')
# 显示动画
plt.show()