运行以下代码时,出现错误"Python TypeError: unsupported operand type(s) for -: 'int' and 'function'"
。即使研究了类似的问题,我也无法解决此问题,所以我将不胜感激!这是我遇到问题的代码部分:
r = 1
def simpson_2var(a,b,f,N,z2):
h = (b-a) / (N)
s = f(a, z2) + f(b, z2)
for i in range(1,N):
if(i%2 ==0):
s += 2*(f(a + i*h, z2))
else:
s += 4*(f(a + i*h, z2))
s *= (h/3.0)
return s
z2 = np.linspace(-10,10,1000,0)
def f(R,z2):
return (R * z2) / ( ( z2**2 + R**2) ** (3/2))
E2 = simpson_2var(0,1,f,1000,z2)
r = 1
z3 = np.linspace(-4*r, 4*r, 1000, 0)
w = simpson_2var(f,0, r, 1000, z3)
plt.plot(w, z3, label = "R=1", color = "cyan")
plt.legend()
plt.xlabel("Electric Field")
plt.ylabel("distance to zz axis'")
plt.grid()
plt.show()
这是我得到的错误(出于行编号的原因,我在这里留下了注释):
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-3bfacd988809> in <module>
1 r = 1
2 z3 = np.linspace(-4*r, 4*r, 1000, 0)
----> 3 w = simpson_2var(f,0, r, 1000, z3)
4 plt.plot(w, z3, label = "R=1", color = "cyan")
5 plt.legend()
<ipython-input-42-7c0c9c6d708d> in simpson_2var(a, b, f, N, z2)
4 # de 1. Usamos esta função logo neste exercício, para função com
5 # variáveis R e z2
----> 6 h = (b-a) / (N)
7 s = f(a, z2) + f(b, z2)
8 for i in range(1,N):
TypeError: unsupported operand type(s) for -: 'int' and 'function'
我将非常感谢您提供的任何帮助。谢谢。
答案 0 :(得分:0)
您的错误来自行h = (b-a) / (N)
,其中b=0
但a
是一个函数,而不是一个值。因此,请在
w = simpson_2var(f,0, r, 1000, z3)
答案 1 :(得分:0)
您的参数似乎在w = simpson_2var(f,0, r, 1000, z3)
和def simpson_2var(a,b,f,N,z2)
之间并不对应。
在调用函数时尝试使用命名参数:
w = simpson_2var(a=0, b=r, f=f, N=1000, z2=z3)