# python计算分段函数值的方法

```# -*- coding:UTF-8 -*-
# 开发时间：2021/9/1 13:27

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-2,2,0.04)
y = np.arange(-2,2,0.04)
# 根据x和y生成网格点
[X,Y] = np.meshgrid(x,y)

Pxy = 0.5457*np.exp(-0.75*Y**2 - 3.75*X**2 - 1.5*X) * (X+Y>1) + \
0.7575*np.exp(-Y**2-6*X**2)*((X+Y<=1) & (X+Y>-1)) + \
0.5457*np.exp(-0.75*Y**2 - 3.75*X**2 + 1.5*X)*(X+Y<=-1)

# 计算分段函数值
print(Pxy)

# 绘制出结果
fig = plt.figure()
ax = plt.gca(projection="3d")

ax.plot_surface(X,Y,Pxy,cmap="rainbow")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()```

```[[4.13780323e-10 7.95789904e-10 1.51222176e-09 ... 8.55819561e-12
3.43799817e-12 1.35484814e-12]
[4.65976503e-10 8.96174556e-10 1.70298047e-09 ... 1.00270794e-11
4.02807814e-12 1.58738717e-12]
[5.23499048e-10 1.00680297e-09 1.91320516e-09 ... 1.17105410e-11
4.70435829e-12 1.85389601e-12]
...
[8.34343054e-13 2.15823201e-12 5.47662686e-12 ... 4.02602659e-09
2.14422875e-09 1.12837657e-09]
[7.16690905e-13 1.85389601e-12 4.70435829e-12 ... 3.59225426e-09
1.91320516e-09 1.00680297e-09]
[6.13662224e-13 1.58738717e-12 4.02807814e-12 ... 3.19753414e-09
1.70298047e-09 8.96174556e-10]]```