本文实例为大家分享了python实现分段线性插值的具体代码,供大家参考,具体内容如下
函数:
算法
这个算法不算难。甚至可以说是非常简陋。但是在代码实现上却比之前的稍微麻烦点。主要体现在分段上。
图像效果
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
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)
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/a19990412/article/details/80470341