- 代码
点击查看代码
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
# 定义函数
def f(x, y):
return (x ** 2 - 2 * x) * np.exp(-x ** 2 - y ** 2 - x * y)
# 生成随机点
np.random.seed(0)
x_random = np.random.uniform(-3, 3, 100)
y_random = np.random.uniform(-4, 4, 100)
z_random = f(x_random, y_random)
# 生成网格点
x_grid = np.linspace(-3, 3, 100)
y_grid = np.linspace(-4, 4, 100)
X_grid, Y_grid = np.meshgrid(x_grid, y_grid)
# 进行插值
Z_grid = griddata((x_random, y_random), z_random, (X_grid, Y_grid), method='cubic')
# 绘制插值结果
plt.contourf(X_grid, Y_grid, Z_grid, levels=20)
plt.colorbar()
plt.title('Interpolation of f(x,y)')
plt.xlabel('x')
plt.ylabel('y')
plt.show()