Reputation: 11
As the title question, I just encounter this problem while doing assignments, but have no idea what it is... Please can anyone help me with this?(I'm a TOTALLY newbie to this and I'm so sorry)
My code is:
#導入數學模組
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
import pylab
#確定坐標軸
n=1000
x=np.linspace(-10, 10, n)
#定義函數
def y(x):
y=pylab.sqrt(2*(pylab.sin(x)+pylab.cos(2*x)+3)/(x+1))
return y
def dy_dx(y, x):
return np.sqrt(2*(pylab.sin(x)+pylab.cos(2*x)+3)/(x+1))
y0=[1]
x=np.arange(-10, 10, 0.01) #(start, stop, step)
y=(dy_dx, y0, x) #求y的一階導數
#繪製函數
plt.plot(x, y(x), color='blue')
plt.plot(x, y, color='green')
#加上細節
plt.grid(True)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('f(x)=sqrt(2(sin(x)+cos(2*x)+3)/(x+1)) and computed derivative')
plt.xlim(0, 20) #定坐標軸範圍
plt.ylim(-1.0, 2.0)
x_main_ticks=np.linspace(0, 20, 4) #定刻度
plt.xticks(x_main_ticks)
#輸出圖像
plt.show()
And the compiler just gave me this:
> Traceback (most recent call last):
File "/home/cg/root/66fb4a93892af/main.py", line 23, in <module>
plt.plot(x, y(x), color='blue')
TypeError: 'tuple' object is not callable
does anyone knows what on just happened to my code?
Upvotes: 1
Views: 68
Reputation: 31
This is because you name the Function y repeatedly. So basically, if you change the code as follow, it works.
#導入數學模組
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
import pylab
#確定坐標軸
n=1000
x=np.linspace(-10, 10, n)
#定義函數
def y_function(x):
return pylab.sqrt(2*(pylab.sin(x)+pylab.cos(2*x)+3)/(x+1))
def dy_dx(y, x):
return np.sqrt(2*(pylab.sin(x)+pylab.cos(2*x)+3)/(x+1))
y0=[1]
x=np.arange(-10, 10, 0.01) #(start, stop, step)
y=(dy_dx, y0, x) #求y的一階導數
#繪製函數
plt.plot(x, y_function(x), color='blue')
plt.plot(x, y[2], color='green')
#加上細節
plt.grid(True)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('f(x)=sqrt(2(sin(x)+cos(2*x)+3)/(x+1)) and computed derivative')
plt.xlim(0, 20)
#定坐標軸範圍
plt.ylim(-1.0, 2.0)
x_main_ticks=np.linspace(0, 20, 4) #定刻度
plt.xticks(x_main_ticks)
#輸出圖像
plt.show()
Upvotes: 1
Reputation: 27186
You assign a tuple to a variable named y after you've defined a function with the same name. This shadows the original function definition.
Ironically, you don't need the y variable. In fact there are a few redundancies in your code.
import matplotlib.pyplot as plt
import pylab
import numpy as np
# 定義函數
def y(x):
return pylab.sqrt(2 * (pylab.sin(x) + pylab.cos(2 * x) + 3) / (x + 1))
x = np.arange(-10, 10, 0.1)
# 繪製函數
plt.plot(x, y(x), color="blue")
plt.plot(x, x, color="green")
# 加上細節
plt.grid(True)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("f(x)=sqrt(2(sin(x)+cos(2*x)+3)/(x+1)) and computed derivative")
plt.xlim(0, 20) # 定坐標軸範圍
plt.ylim(-1.0, 2.0)
x_main_ticks = np.linspace(0, 20, 4) # 定刻度
plt.xticks(x_main_ticks)
# 輸出圖像
plt.show()
Upvotes: 0