2016-12-04 85 views
0

我有一個函數可以繪製。 現在我想繪製這個函數的對數。 Python說log10()沒有爲函數定義(我知道這一點)。 所以問題是:如何繪製函數的對數,如f(x,a)= a *(x ** 2)?Python:繪製函數的對數

+0

是你的問題計算對數基10或繪製值是多少?如果是後者,那麼與繪製其他任何東西有什麼不同呢?另外,你的'f(x,a)'是兩個值的函數。你想繪製變化'x's和常量'a'嗎? –

+0

x應該是我的變量,並且是繪製函數時可以放入的一個參數。問題是我無法定義正確的功能,例如g(x,a)= log10(f(x,a)),因爲我不能在日誌中放入函數。 – user7248647

+0

我的意思是我基​​本上想告訴程序是:給定f(x,a)(我已經繪製)在該函數的每個點上使用log10()並繪製它 – user7248647

回答

0

這是令人誤解的說,matplotlib可以繪製功能。 Matplotlib只能繪製值。

所以,如果你的函數是

f = lambda x,a : a * x**2 

你首先需要創建值的數組,x和定義a

a=3.1 
x = np.linspace(-6,6) 

然後,您可以通過

繪製陣列 y = f(x,a)
ax.plot(x,y) 

如果您現在想繪製日誌算術的f,你真正需要做的是繪製你的數組的對數y。所以,你需要創建一個新的數組

y2 = np.log10(y) 

,並繪製它

ax.plot(x,y2) 

在某些情況下,而不是顯示線性比例函數的對數,它可能是更好的顯示功能本身在對數尺度上。這可以通過將matplotlib中的座標軸設置爲對數並在該對數座標上繪製初始數組y來完成。

ax.set_yscale("log", nonposy='clip') 
ax.plot(x,y) 

所以這裏的所有三種情況中的展示例如:

import matplotlib.pyplot as plt 
import numpy as np 

#define the function 
f = lambda x,a : a * x**2 

#set values 
a=3.1 
x = np.linspace(-6,6) 

#calculate the values of the function at the given points 
y = f(x,a) 
y2 = np.log10(y) 
# y and y2 are now arrays which we can plot 

#plot the resulting arrays 
fig, ax = plt.subplots(1,3, figsize=(10,3)) 

ax[0].set_title("plot y = f(x,a)") 
ax[0].plot(x,y) # .. "plot f" 

ax[1].set_title("plot np.log10(y)") 
ax[1].plot(x,y2) # .. "plot logarithm of f" 

ax[2].set_title("plot y on log scale") 
ax[2].set_yscale("log", nonposy='clip') 
ax[2].plot(x,y) # .. "plot f on logarithmic scale" 

plt.show() 

enter image description here

0

如果你的困難是計算對數基10,使用

def g(x, a): 
    return math.log(f(x, a))/math.log(10) 

或只是

def log10(x): 
    return math.log(x)/math.log(10) 

這給出了一個錯誤的非正面的價值觀,這是你想要的。它使用標準的身份

數×基B的數=(X)/日誌(二)

甚至根本不管哪個基礎,log()功能使用:你會得到相同的回答任何基地。