分段线性插值Python实现(同时估计误差)

33 篇文章 1 订阅
25 篇文章 8 订阅

函数

y = 1 1 + x 2 y = \frac{1}{1+x^2} y=1+x21

算法

这个算法不算难。甚至可以说是非常简陋。但是在代码实现上却比之前的稍微麻烦点。主要体现在分段上。

图像效果

这里写图片描述

代码

import numpy as np
from sympy import *
import matplotlib.pyplot as plt


def f(x):
    return 1 / (1 + x ** 2)


def cal(begin, end):
    by = f(begin)
    ey = f(end)
    I = (n - end) / (begin - end) * by + (n - begin) / (end - begin) * ey
    return I


def calnf(x):
    nf = []
    for i in range(len(x) - 1):
        nf.append(cal(x[i], x[i + 1]))
    return nf


def calf(f, x):
    y = []
    for i in x:
        y.append(f.subs(n, i))
    return y


def nfSub(x, nf):
    tempx = np.array(range(11)) - 5
    dx = []
    for i in range(10):
        labelx = []
        for j in range(len(x)):
            if x[j] >= tempx[i] and x[j] < tempx[i + 1]:
                labelx.append(x[j])
            elif i == 9 and x[j] >= tempx[i] and x[j] <= tempx[i + 1]:
                labelx.append(x[j])
        dx = dx + calf(nf[i], labelx)
    return np.array(dx)


def draw(nf):
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    x = np.linspace(-5, 5, 101)
    y = f(x)
    Ly = nfSub(x, nf)
    plt.plot(x, y, label='原函数')
    plt.plot(x, Ly, label='分段线性插值函数')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()

    plt.savefig('1.png')
    plt.show()


def lossCal(nf):
    x = np.linspace(-5, 5, 101)
    y = f(x)
    Ly = nfSub(x, nf)
    Ly = np.array(Ly)
    temp = Ly - y
    temp = abs(temp)
    print(temp.mean())


if __name__ == '__main__':
    x = np.array(range(11)) - 5
    y = f(x)

    n, m = symbols('n m')
    init_printing(use_unicode=True)

    nf = calnf(x)
    draw(nf)
    lossCal(nf)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥宅_Sean

公众号“肥宅Sean”欢迎关注

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值