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

算法
這個(gè)算法不算難。甚至可以說(shuō)是非常簡(jiǎn)陋。但是在代碼實(shí)現(xiàn)上卻比之前的稍微麻煩點(diǎn)。主要體現(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)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
django queryset 去重 .distinct()說(shuō)明
這篇文章主要介紹了django queryset 去重 .distinct()說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
python Selenium等待元素出現(xiàn)的具體方法
在本篇文章里小編給大家分享的是一篇關(guān)于python Selenium等待元素出現(xiàn)的具體方法,以后需要的朋友們可以學(xué)習(xí)參考下。2021-08-08
Python?jieba庫(kù)文本處理詞性標(biāo)注和關(guān)鍵詞提取進(jìn)行文本情感分析
這篇文章主要為大家介紹了Python使用中文文本處理利器jieba庫(kù)中的詞性標(biāo)注和關(guān)鍵詞提取功能進(jìn)行文本情感分析實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
在Python反編譯中批量pyc轉(zhuǎn)?py的實(shí)現(xiàn)代碼
這篇文章主要介紹了在Python反編譯中批量pyc轉(zhuǎn)?py的實(shí)現(xiàn)代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
控制Python浮點(diǎn)數(shù)輸出位數(shù)的操作方法
在python的輸出結(jié)果中,尤其是浮點(diǎn)數(shù)的輸出,當(dāng)我們需要寫入文本文件時(shí),最好是采用統(tǒng)一的輸出格式,這樣也能夠增強(qiáng)結(jié)果的可讀性,這篇文章主要介紹了控制Python浮點(diǎn)數(shù)輸出位數(shù)的方法,需要的朋友可以參考下2022-04-04
Python中uuid模塊生成唯一標(biāo)識(shí)符的方法詳解
這篇文章主要給大家介紹了關(guān)于Python中uuid模塊生成唯一標(biāo)識(shí)符的相關(guān)資料,uuid庫(kù)是Python標(biāo)準(zhǔn)庫(kù)中的一個(gè)功能強(qiáng)大的庫(kù),可以用于生成全局唯一標(biāo)識(shí)符(UUID),文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08

