Python绘图--函数图像(并计算三个函数相交围成的图像面积)

题目给出三个已知函数方程:

需要,首先画出函数图像,并且给所围图形打上阴影,并用计算其积分,运行效果如下:

具体代码:

import numpy as np # 给numpy库起个别名
from matplotlib import pyplot as plt  #matplotlib是Python语言及其数值计算库NumPy的绘图库。

#设置图像细节
#plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
#plt.legend(loc= 'lower left') # 设置图例位置location
plt.ylim(-10, 10)  # y轴显示区间
plt.xlim(-1, 3)  # x轴显示区间


ax = plt.gca() #可以使用 plt.gcf()和 plt.gca()获得当前的图表和坐标轴(分别表示 Get Current Figure 和 Get Current Axes)
ax.xaxis.set_ticks_position('bottom') #设置x轴为下边框
ax.spines['bottom'].set_position(('data', 0))  # spines是脊柱的意思,移动x轴
ax.spines['top'].set_color('none')  # 设置顶部支柱的颜色为空
ax.spines['right'].set_color('none')  # 设置右边支柱的颜色为空
plt.grid(True, linestyle='--', alpha=0.5)  # 网格

X1 = np.arange(-1, 3, 0.1)  # x范围
X2 = np.ma.masked_array(X1, mask=((X1 < 0.000001) & (X1 > -0.000001)))  # 反比例函数去掉X为零的情况

F1 = np.exp(-X1) + 3  # 指数函数
F2 = 2 * X1 - 2  # 一次函数
F3 = 1 / X2  # 反比例函数


def f1(x):  # 指数函数
    return np.exp(-x) + 3


def f2(x):  # 一次函数
    return 2 * float(x) - 2 # 强制类型转换float


def f3(x):  # 反比例函数
    return 1 / float(x)



def root(f, g, a, b, eps1):
    while b - a > eps1:
        # 二分法 求f = g 方程的根
        x = (a + b) / 2
        y = f(x) - g(x)
        ya = f(a) - g(a)
        yb = f(b) - g(b)
        if y * ya < 0:
            b = x
        elif y * yb < 0:
            a = x
    r = "%.4f" % ((a + b) / 2)
    return r


def integral(f, a, b, eps2):
    # 设置初始积分
    n = 20
    # n对应的积分值
    R = [] # 一个空的list
    I = 0
    h = (b - a) / n
    # 计算积分
    for i in range(0, n - 1):
        I += (f(a + (i + 0.5) * h))
    R.append(h * I) # 记录h*I 的值
    while (1):
        # 更新
        n *= 2
        I = 0
        h = (b - a) / n
        # 计算
        for i in range(0, n - 1): # 从0 ~n-1的循环
            I += (f(a + (i + 0.5) * h)) # 矩形公式
        R.append(h * I)
        # 判断
        if (abs(R[-1] - R[-2]) / 3 < eps2):
            break
    c = []  # 存下每个积分点的横坐标
    for i in range(0, n - 1):
        c.append(a + h * i)
    # print("R:", R[-1])
    return c, R[-1]


def drawRomberg(f1, f2, a, b, eps2, n): #画出求积部分
    x1, y1 = integral(f1, a, b, eps2)
    x1_ = []
    for i in range(len(x1)):
        if i % n == 0:
            x1_.append(x1[i])
        if i == len(x1) - 1:
            x1_.append(x1[i])
    for i in x1_:
        line = [i, f1(i), i, f2(i)]
        plt.plot(line[::2], line[1::2], color='red',
                 linewidth=1, linestyle="--")


if __name__ == '__main__': #“if __name__==’__main__:”也像是一个标志,象征着Java等语言中的程序主入口,告诉其他程序员,代码入口在此——这是“if __name__==’__main__:”这条代码的意义之一。
    # 计算四个交点的坐标
    x4 = "%.4f" % float(root(f1, f2, 2, 3, 0.001))
    y4 = "%.4f" % float(f2(x4))
    x2 = "%.4f" % float(root(f1, f3, 0.1, 1, 0.001))
    y2 = "%.4f" % float(f3(x2))
    x3 = "%.4f" % float(root(f2, f3, 1, 2, 0.001))
    y3 = "%.4f" % float(f2(x3))
    x1 = "%.4f" % float(root(f2, f3, -1, -0.1, 0.001))
    y1 = "%.4f" % float(f2(x1))
    print("x1:%.4f" % float(x1), "y1:%.4f" % float(y1))
    print("x2:%.4f" % float(x2), "y2:%.4f" % float(y2))
    print("x3:%.4f" % float(x3), "y3:%.4f" % float(y3))
    print("x4:%.4f" % float(x4), "y4:%.4f" % float(y4))

    # 画出初始的三条函数
    plt.plot(X1, F1, linewidth=1.5, linestyle="-", label="f1")
    plt.plot(X1, F2, linewidth=1.5, linestyle="-", label="f2")
    plt.plot(X2, F3, linewidth=1.5, linestyle="-", label="f3")

    # 画出四个交点围成的三角形
    polygon = [[float(x2), float(y2)], [float(x3), float(y3)], [
        float(x4), float(y4)]]
    # line_area = polygon+[polygon[0]]
    # plt.plot([i[0] for i in line_area], [i[1] for i in line_area])

    # 画出三个焦点
    plt.scatter(polygon[0][0], polygon[0][1], s=50, c='r')
    plt.scatter(polygon[1][0], polygon[1][1], s=50, c='r')
    plt.scatter(polygon[2][0], polygon[2][1], s=50, c='r')

    # 计算面积
    I = integral(f1, float(x2), float(x4), 0.001)[1] - integral(f2, float(x3),
                                                                float(x4), 0.001)[1] - \
        integral(f3, float(x2), float(x3), 0.001)[1]

    # 画出求积部分
    drawRomberg(f1, f3, float(x2), float(x3), 0.001, 80)
    drawRomberg(f1, f2, float(x3), float(x4), 0.001, 80)

    # 显示计算结果
    plt.text(1.5, 6, "I = {}".format("%.4f" % float(I)))

    # 显示
    plt.legend(loc='upper left')
    plt.show()


 

好的,以下是使用Python实现Cohen-Sutherland算法的代码,绘制图形的例子: ```python from matplotlib import pyplot as plt from matplotlib import patches as patches # 定义编码函数 def encode(x, y, xmin, ymin, xmax, ymax): code = 0 if x < xmin: # 左边界 code |= 1 elif x > xmax: # 右边界 code |= 2 if y < ymin: # 下边界 code |= 4 elif y > ymax: # 上边界 code |= 8 return code # 定义Cohen-Sutherland算法函数 def cohen_sutherland(x1, y1, x2, y2, xmin, ymin, xmax, ymax): code1 = encode(x1, y1, xmin, ymin, xmax, ymax) code2 = encode(x2, y2, xmin, ymin, xmax, ymax) accept = False while True: if code1 == 0 and code2 == 0: # 完全在窗口内 accept = True break elif code1 & code2 != 0: # 完全在窗口外 break else: # 部分在窗口内,需要截取 code_out = code1 if code1 != 0 else code2 x, y = 0, 0 if code_out & 1: # 与左边界相交 x = xmin y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1) elif code_out & 2: # 与右边界相交 x = xmax y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1) elif code_out & 4: # 与下边界相交 y = ymin x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1) elif code_out & 8: # 与上边界相交 y = ymax x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1) if code_out == code1: # 更新第一个点的编码 x1, y1 = x, y code1 = encode(x1, y1, xmin, ymin, xmax, ymax) else: # 更新第二个点的编码 x2, y2 = x, y code2 = encode(x2, y2, xmin, ymin, xmax, ymax) return accept, x1, y1, x2, y2 # 定义绘图函数 def plot(xmin, ymin, xmax, ymax, x1, y1, x2, y2, accept): fig, ax = plt.subplots() ax.set_xlim([xmin-1, xmax+1]) ax.set_ylim([ymin-1, ymax+1]) ax.add_patch(patches.Rectangle((xmin, ymin), xmax-xmin, ymax-ymin, fill=False)) if accept: ax.plot([x1, x2], [y1, y2], color='green') else: ax.plot([x1, x2], [y1, y2], color='red') plt.show() # 测试 xmin, ymin, xmax, ymax = 0, 0, 10, 10 x1, y1, x2, y2 = 3, 1, 7, 9 accept, x1, y1, x2, y2 = cohen_sutherland(x1, y1, x2, y2, xmin, ymin, xmax, ymax) plot(xmin, ymin, xmax, ymax, x1, y1, x2, y2, accept) ``` 该代码使用了matplotlib库来绘制图形,首先定义了一个编码函数`encode`,用于对点进行编码。然后定义了Cohen-Sutherland算法函数`cohen_sutherland`,该函数根据点的编码来判断是否需要截取线段,返回是否完全在窗口内以及截取后的线段端点坐标。最后定义了绘图函数`plot`,该函数使用了matplotlib绘制窗口和线段,绿色表示完全在窗口内,红色表示完全在窗口外。在测试代码中,定义了一个10x10的窗口和一条从(3,1)(7,9)的线段,调用Cohen-Sutherland算法函数绘图函数进行测试。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值