Larange插值

Larange插值使用Python仿真
理论:略

import matplotlib.pyplot as mpl
import matplotlib.pyplot as plt
import numpy as np

def Larange(x,y,a):
    sum=0.0
    for i in range(len(y)):
        t=y[i]
        for j in range(len(y)):
            if i != j:
                t *=(a-x[j])/(x[i]-x[j])
        sum += t
    return sum

"""
@brief: 获得拉格朗日插值基函数
@param: xi      xi为第i个插值节点的横坐标
@param: x_set   整个插值节点集合
@return: 返回值为参数xi对应的插值基函数
"""
def get_li(xi, x_set = []):
    def li(Lx):
        W = 1; c = 1
        for each_x in x_set:
            if each_x == xi:
                continue
            W = W * (Lx - each_x)

        for each_x in x_set:
            if each_x == xi:
                continue
            c = c * (xi - each_x)

        # 这里一定要转成float类型,否则极易出现严重错误. 原因就不说了
        return W / float(c)    
    return li

"""   
@brief: 获得拉格朗日插值函数
@param: x       插值节点的横坐标集合
@param: fx      插值节点的纵坐标集合 
@return: 参数所指定的插值节点集合对应的插值函数
"""

def get_Lxfunc(x = [], fx = []):
    set_of_lifunc = []
    for each in x:  # 获得每个插值点的基函数
        lifunc = get_li(each, x)
        set_of_lifunc.append(lifunc)    # 将集合x中的每个元素对应的插值基函数保存

    def Lxfunc(Lx):
        result = 0
        for index in range(len(x)):
            result = result + fx[index]*set_of_lifunc[index](Lx)    #根据根据拉格朗日插值法计算Lx的值
            print(fx[index])
        return result

    return Lxfunc

if __name__ == '__main__':  

    sr_x = [i for i in range(-50, 50, 10)]
    sr_fx = [i**2 for i in sr_x]

    Lx = get_Lxfunc(sr_x, sr_fx)            # 获得插值函数
    tmp_x = [i for i in range(-45, 45)]     # 测试用例
    tmp_y = [Lx(i) for i in tmp_x]          # 根据插值函数获得测试用例的纵坐标

    ''' 画图 '''
    plt.figure("play")
    ax1 = plt.subplot(111)
    plt.sca(ax1)
    plt.plot(sr_x, sr_fx, linestyle = ' ', marker='o', color='b')
    plt.plot(tmp_x, tmp_y, linestyle = '--', color='r')
    plt.show()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值