簡體   English   中英

Plot 在使用 numpy 和 matplotlib 時不是從 0 開始

[英]Plot not starting from 0 while using numpy and matplotlib

所以我目前正在用numpy和matplotlib做一個數學作業,是關於數值微分法的。 所以首先我定義了一個數學上的 function 如下:

def f_x(x):
y = -(3.71*x**2.3)
return y.real

然后我輸入數值微分的代碼:

def cal_derivative(a_function, x, delta_x, method): 
if method == "forward":
    delta_y = a_function(x + delta_x) - a_function(x)
    derivative = delta_y/(delta_x)
if method == "backward":
    delta_y = a_function(x).real - a_function(x - delta_x).real
    derivative = delta_y/(delta_x)
if method == "central":
    delta_y = a_function(x + delta_x).real - a_function(x - delta_x).real
    derivative = delta_y/(2*delta_x)
return derivative.real

最后我 plot 的數值導數的grpah:

import numpy as np
import matplotlib.pyplot as plt
x_increment = 1
x_range = np.arange(0, 8+x_increment, x_increment)
y_1 = cal_derivative(f_x, x_range , 1, "forward")
y_2 = cal_derivative(f_x, x_range , 1, "backward")
y_3 = cal_derivative(f_x, x_range , 1, "central")
y_4 = analytical_derivative(x_range)
plt.plot(x_range,y_1,label = "Result for forward difference method")
plt.plot(x_range,y_2,label = "Result for backward backward method")
plt.plot(x_range,y_3,label = "Result for central divided difference method")
plt.plot(x_range,y_4,label = "Analytical differentiation result")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.title("Result comparsion for x∈[0,8], Δx=1.0")
plt.ylabel("y")
plt.xlabel("x")

然后,我期待我的數值微分代碼 output 在圖表上從 x=0 到 x=8 繪制。 但是,我得到了這樣的東西:

在此處輸入圖像描述

在我得到的plot中,后向中心差分法的導數並沒有像我預期的那樣從0開始。 我懷疑這是因為對於 x<1 和 delta_x = 1,我的代碼涉及一個負數的小數次冪(在這種情況下為 2.3),因此導致了這個錯誤,但我不確定。 我嘗試了很多次來解決這個問題,但都沒有成功。 有人可以幫我解決這個問題嗎? 任何幫助,將不勝感激。 非常感謝。

您可能需要將x_range設置為復雜類型,如下所示:

x_range = np.arange(0, 8+x_increment, x_increment) + 0j

這樣做,Numpy 將能夠評估f_x計算復數值。 如果您要在x_range中使用 dtype dtype=float (就像您現在所做的那樣),那么當x為負時,對f_x的計算將創建Nan值。

在這里我刪除了解析解,因為你沒有提供 function:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM