溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python實(shí)現(xiàn)分段線性插值

發(fā)布時(shí)間:2020-10-02 08:15:42 來源:腳本之家 閱讀:369 作者:肥宅_Sean 欄目:開發(fā)技術(shù)

本文實(shí)例為大家分享了Python實(shí)現(xiàn)分段線性插值的具體代碼,供大家參考,具體內(nèi)容如下

函數(shù):

Python實(shí)現(xiàn)分段線性插值

算法

這個(gè)算法不算難。甚至可以說是非常簡陋。但是在代碼實(shí)現(xiàn)上卻比之前的稍微麻煩點(diǎn)。主要體現(xiàn)在分段上。

圖像效果

Python實(shí)現(xiàn)分段線性插值

代碼

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='原函數(shù)')
 plt.plot(x, Ly, label='分段線性插值函數(shù)')
 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)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI