《高等数学》同济大学出版:分段函数
编写 test_sin_1_x.py 如下
# -*- coding: utf-8 -*-
""" 绘制分段函数 y = sin(1/x) 当 x!=0; y=0 当x=0; 在 -2<=x<=2 的曲线 """
import numpy as np
from matplotlib import pyplot as plt
# 用于正常显示中文标题,负号
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(0.01, 2.01, 0.01)
y = np.sin(1/x)
print(len(x))
x_1 = np.arange(-2.0, 0.0, 0.01)
y_1 = np.sin(1/x_1)
print(len(x_1))
# 可视化
fig = plt.figure()
axes = fig.add_subplot(111)
axes.plot(x, y, label='0.01<=x<=2.0') # 画曲线
axes.plot(x_1, y_1, label='-2.0<=x<0')
#axes.axis('scaled') # 用缩尺制图
axes.axis('equal')
plt.title('分段函数 y = sin(1/x) 当 x!=0 的曲线')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()
运行 python test_sin_1_x.py
编写 test_2sqrt_x_x1.py 如下
# -*- coding: utf-8 -*-
""" 绘制分段函数 y=2sqrt(x) 当0<=x<=1; y=1+x 当x>1; 在 0<=x<=2 的曲线 """
import numpy as np
from matplotlib import pyplot as plt
# 用于正常显示中文标题,负号
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.arange(0., 1., 0.01)
y = np.sqrt(x)*2
print(len(x))
x1 = np.arange(1.0, 2.0, 0.01)
y1 = 1+x1
print(len(x1))
# 可视化
fig = plt.figure()
axes = fig.add_subplot(111)
axes.plot(x, y, label='2sqrt(x)') # 画曲线
axes.plot(x1,y1, label='1+x')
#axes.axis('scaled') # 用缩尺制图
axes.axis('equal')
plt.title('分段函数 y=2sqrt(x) 当0<=x<=1; y=1+x 当x>1 的曲线')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()
运行 python test_2sqrt_x_x1.py