【问题标题】:TypeError: 'numpy.ndarray' object is not callable, TypeError: unsupported operand type(s) for /: 'int' and 'list'TypeError:“numpy.ndarray”对象不可调用,TypeError:/:“int”和“list”不支持的操作数类型
【发布时间】:2019-11-22 21:17:27
【问题描述】:

所以基本上我有多个数组,我需要用这些数组计算一些东西。问题是这些数组中的一些有时等于零并且是除数。

我想通过过滤我的数组并说出类似“if r >= rs: print("0"), else: print(H)”之类的话来解决这个问题,但它不起作用。我还尝试使用 map 函数来表示如果半径 r

def Max(r):
    if r < 0.00001:
      result = 0.00001
    else:
          result = r
    return(result)

# radius array (trying to apply Max to all r)
r22 = map(Max, zz[:, 1]) # zz is an odeint function defined before

def Hamiltonian(r, pt, pr, pphi): #all values are given in the code
H = (-((1-rs/r)*-1)(pt*2)/2 + (1-rs/r)(pr*2)/2 + (pphi2)/(2(r**2)))
return(H)

我收到三个错误消息,“TypeError: unsupported operand type(s) for /: 'int' and 'map'”、“TypeError: 'numpy.ndarray' object is not callable”和 TypeError: unsupported operand type (s) for /: 'int' 和 'list'。有谁知道为什么?理想情况下,我希望 H 为所有半径 = 0 自动打印 0 并忽略除以零。谁能帮帮我??

【问题讨论】:

    标签: python arrays function numpy-ndarray


    【解决方案1】:

    您的“H 公式”写得不正确,我相信缺少一些乘数符号...

    H = (-((1-rs/r)*-1)*(pt*2)/2 + (1-rs/r)*(pr*2)/2 + (pphi*2)/(2*(r**2)))
    

    对于除法,可以尝试处理异常吗?比如:

    def hamiltonian(r, pt, pr, pphi):
        while True:
            try:
                H = (-((1 - rs / r) * -1) * (pt * 2) / 2 + (1 - rs / r) * (pr * 2) / 2 + (pphi * 2) / (2 * (r ** 2)))
                return(H)
            except ZeroDivisionError:
                H = 0
                return(H)
    
    print(hamiltonian(r, pt, pr, pphi))
    

    check this to learn about handling of errors and exceptions

    【讨论】:

    • 感谢您这么快回答!不幸的是,我尝试了这种方法,但仍然收到一条错误消息“TypeError:'numpy.ndarray' object is not callable”,它基本上告诉我我尝试将 numpy 数组作为函数调用,对吗?你知道如何解决这个问题吗?
    • 是的,绝对正确,不敢相信我没看到……抱歉打扰了 ;)
    • 不客气,我再次编辑了答案,并将异常处理包含在您的代码中。确保你的公式是正确的:)
    猜你喜欢
    • 2013-04-26
    • 2012-12-12
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2015-12-11
    • 1970-01-01
    • 2014-12-28
    相关资源
    最近更新 更多