不要怪女人现实,女人之所以现实,只因经历过爱情的伤生活的磨砺。只有懂得女人为何如此现实的男人,才能够给予女人一份期待中的现实生活。
本文实例为大家分享了Python实现分段线性插值的具体代码,供大家参考,具体内容如下
函数:
算法
这个算法不算难。甚至可以说是非常简陋。但是在代码实现上却比之前的稍微麻烦点。主要体现在分段上。
图像效果
代码
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)
到此这篇关于Python实现分段线性插值就介绍到这了。要得到世界上最好的东西,先把最好的自己交给世界。从现在开始,不沉溺幻想,不庸人自扰,踏实工作,好好生活;从现在开始,做出的每个选择,都要保证自己比现在更快乐,因为你值得拥有更好的自己。更多相关Python实现分段线性插值内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!