2017-09-17 21 views
0

我試圖在Python中定義heaviside函數,但得到一個奇怪的錯誤。我不確定'type'是指什麼,因爲0可以是一個整數。請提醒TypeError:'> =''type'和'int'的實例之間不支持

#Part A - Plot function against values of variable x 
import numpy as np 
import matplotlib.pyplot as plt 
import scipy.integrate as quad 
import math 

#make heaviside "theta" function 

x = int 
def heaviside (x): 
    if (x >= 0): 
     return 1 
    else: 
    return 0 

#plot 
x = int 
y = heaviside(x)*[1-heaviside(x-1)] 
plt.plot(x, y) 
+2

'''x = int'''這是怎麼回事?'你有多少python經驗? – sascha

+1

您是否閱讀過錯誤信息?您將'x'設置爲'int',它是一個'type',並將其與'int'比較爲'0'。 – Jerfov2

+0

我想op是試圖簡單地使用y作爲函數來計算他們圖的y。 afaik你需要給pyplot.plot一個y值的序列,沒有辦法給出公式 –

回答

0

您在設定x不正確。如果你希望x是一個整數,只需使用如下所示的賦值運算符即可。

x = 5 
+0

不會將x設置爲一個特定的整數擊敗定義一個函數其中x取任何值? –

+0

@atemptcode你誤解了matplotlib,你需要給它一個y值的序列來繪製圖表,而不是公式 –

1

當您聲明x = int時,您將x等同於數據類型int,而不是該數據類型的實例。 你可以運行這樣的代碼來看看它。

>>> x = int 
>>> x(4.5) 
4 

如果傳遞的X數值代替,如x = 4,那麼你將不會有這個錯誤等同於運行

>>>int(4.5) 
4 

下面的代碼不會再提出這個錯誤。由此產生的情節並沒有多少顯示;但沒有TypeError:無法編輯的類型:type()> = int()

#Part A - Plot function against values of variable x 
import numpy as np 
import matplotlib.pyplot as plt 
import scipy.integrate as quad 
import math 

#make heaviside "theta" function 


def heaviside (x): 
    if (x >= 0): 
     return 1 
    else: 
     return 0 

#plot 
x = 5 
y = heaviside(x)*[1-heaviside(x-1)] 
plt.plot(x, y) 
+1

經過多年的python(可能是因爲我從不需要它),我從來沒有見過這種例子。很不錯(儘管它可能比問題所要求的更高一些)! – sascha

+0

好吧,我試着設置x等於一個真正的整數值,並得到相同的錯誤。我也試過沒有定義x,仍然得到相同的錯誤 –

+0

@atemptcode你的問題是y的定義。閱讀重複鏈接,也許一些numpy/matplotlib教程。 – sascha

相關問題