0

我需要比較插值函數的最大偏差與函數f(x)=exp(x)的真實值。我不知道如何找到發生這種情況的x值,因爲我使用x=np.linspace()來繪製插值和真實函數。找到插值函數的最大偏差在哪裏?

我的任務是先給出以下值x=[0,1,2]f(x)=exp(x)線性內插,然後再與x=[0,0.5,1,1.5,2]。(我做了)

x_1=np.linspace(0,1,num=20) 
x_2=np.linspace(1,2,num=20) 
x_3=np.linspace(0,2,num=20) 
y_1=np.empty(20) 
y_2=np.empty(20) 
y_3=np.empty(20) 

def interpolation(x,a,b): 
    m=(f(b)-f(a))/(b-a) 
    z=f(a) 
    y=m*(x-a) 
    return y+z 

n=0 
for k in x_1: 
    y_1[n]=interpolation(k,0,1) 
    n+=1 

n_1=0 
for l in x_2: 
    y_2[n_1]=interpolation(l,1,2) 
    n_1+=1 


x1=np.linspace(0,1,num=20) 
x2=np.linspace(1,2,num=20) 
y1=np.empty(20) 
y2=np.empty(20) 


n1=0 
for p1 in x1: 
    y1[n1]=f(p1)#true value of f(x)=exp(x) 
    n1+=1 

n2=0 
for p2 in x2: 
    y2[n2]=f(p2) 
    n2+=1 

#only gives the distance of the deviation, only idea I've got so far 
print(max(abs(y1-y_1))) 
print(max(abs(y2-y_2))) 

回答

1

如果你想找到x與最大的錯誤,從採樣的點,您需要找到np.argmax函數error陣列中最大錯誤的索引:

# Given the following variables 
# x - x values 
# y_int - y values interpolated in the given range 
# y_eval - y values obtained by evaluating the function 

abs_error = abs(y_eval - y_int) 

index_max_error = abs_error.argmax() 

x_max_error = x[index_max_error] 
相關問題