python实现高数公式作图

使用python中的matplotlib模块制作函数图像,并且按照图示要求。

img

希望有用
https://b23.tv/rSqsGKF

参考链接

  1. y=sin(x)

img

  1. 求解:函数 sin(x)+x+1=0的值
    可以理解为 求y=-sin(x)-x-1 与 y=0这俩条线的交点的值
    求解值,可以先缩小俩条曲线x与y的范围,然后计算相邻点的值 < 某个值0.1等,则认为相交。

    img


    其中3个解为:
    sin(x)+x+1=0 val: -0.5114183327010013
    sin(x)+x+1=0 val: -0.5110977947300198
    sin(x)+x+1=0 val: -0.5107772567590383
import numpy as np
from matplotlib import pyplot as plt

# 1. 绘制y=sin(x)
# 定义 x 变量的范围 (-15,15) 数量 100
x = np.linspace(-15, 15, 100)
y = np.sin(x)

# 开始绘图
# 绘制 y=-x-exp(x) 的图像,设置 color 为 red,线宽度是 1,线的样式是 --
plt.plot(x, y, color='red', linewidth=1.0, linestyle='--')
plt.title('y=sin(x)')
plt.show()

# 2. y=1+x+sin(x) 其中x范围为[-Π/2,Π/2]
# 绘制y=-1-x-np.sin(x)  与另一条线y=0相交以查看是否有解
x1 = np.linspace(-np.pi / 2, np.pi / 2, 100)
y1 = -1 - x1 - np.sin(x1)
plt.plot(x1, y1, color='red', linewidth=1.0, linestyle='dashdot')
x2 = x1
y2 = np.zeros(len(x2))
plt.plot(x2, y2, color='green', linewidth=1.0, linestyle='solid')
plt.title('y = -1-x-np.sin(x) & y=0')
plt.show()

# 从上图可以看到俩条线有交点,交点就是其解
# 下边用算法计算俩条线的交点值
x1 = x1.tolist()
x2 = x2.tolist()
y1 = y1.tolist()
y2 = y2.tolist()
x_begin = max(x1[0], x2[0])
x_end = min(x1[-1], x2[-1])

points1 = [t for t in zip(x1, y1) if x_begin <= t[0] <= x_end]
points2 = [t for t in zip(x2, y2) if x_begin <= t[0] <= x_end]

idx = 0
nrof_points = len(points1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x1, y1, color='red', linewidth=1.0, linestyle='dashdot')
ax.plot(x2, y2, color='green', linewidth=1.0, linestyle='solid')
while idx < nrof_points - 1:
    # 迭代逼近俩条线的交点
    y_min = min(points1[idx][1], points1[idx + 1][1])
    y_max = max(points1[idx + 1][1], points2[idx + 1][1])

    x3 = np.linspace(points1[idx][0], points1[idx + 1][0], 100)
    y1_new = np.linspace(points1[idx][1], points1[idx + 1][1], 100)
    y2_new = np.linspace(points2[idx][1], points2[idx + 1][1], 100)

    # 近似距离小于0.001认为相交
    tmp_idx = np.argwhere(np.isclose(y1_new, y2_new, atol=0.001)).reshape(-1)
    if len(tmp_idx) > 0:
        for i in tmp_idx:
            print("sin(x)+x+1=0 val: ", x3[i])
            ax.plot(x3[i], y2_new[i], 'ro')  # 绘制逼近求解值的点

    idx += 1

plt.title('y = -1-x-np.sin(x) & y=0')
plt.show()