【问题标题】:type numpy.ndarray doesn't define __round__ method类型 numpy.ndarray 没有定义 __round__ 方法
【发布时间】:2019-11-07 14:35:24
【问题描述】:

这是代码:

import numpy as np
def f_func(state,time,cd,mass,rho,A):
    """Calculate the differential of state vector as a function of time

        Args:
        state (list): the state vector at time t
        time (float): the time t
        cd (float): the dimensionless drag coefficient
        mass (float): mass of the object in kg
        rho (float): density of air (kg/m3)
        A (float): cross-sectional area of object (kg)

        Returns:
        (list): the differential of the state vector at time t
    """
    # defensive program - check shape of state vector
    assert len(state)==2, "Expected length 2 state vector"
    vy,y = state
    # YOUR CODE HERE

    X = np.array([[vy],[y]])

    # we know d**2 y / d t**2 = a = -g + 1/(2mass)*(cd*rho*A*vy**2)
    d2ydt2 = -g + (1/(2*mass))*(cd*rho*A*vy**2)
    a = d2ydt2
    # WE KNOW d y / d t = vy
    dXdt = np.array([[-g + (1/(2*mass))*(cd*rho*A*(vy)**2)],[vy]])

    return dXdt

检查了以下内容:

 from nose.tools import assert_equal, assert_almost_equal
 a,vy = f_func([0.,78.],0.0,0.5,1,1.2,1)
 assert_almost_equal(a, -9.8)
 assert_almost_equal(vy, 0.0)
 a,vy = f_func([-2.,78.],0.0,0.5,1,1.2,1)
 assert_almost_equal(a,-8.6)
 assert_almost_equal(vy,-2) 
 '''

错误信息,我不明白:

type numpy.ndarray doesn't define __round__ method (error from line 6)

【问题讨论】:

  • 显示完整的回溯。
  • 回溯是否显示asset_almost_equal 调用round 有什么不同?如果a 是一个数组,那么该差异也将是一个数组。正如其他人指出的那样,数组上的round 会引发此错误。那些 nose.tools(和 unittest)断言是为 Python 标量设计的,而不是 numpy 数组。

标签: python numpy


【解决方案1】:

这些变量不是浮点数,它们是 numpy 类型。 Numpy 类型不实现 .__round__() 方法,这就是您收到错误的原因。这些类型有自己的 .round() 方法,这是 numpy 使用的。你能换成:

assert np.isclose(a, -9,8)
assert np.isclose(vy, 0.0)
assert np.isclose(a, -8.6)
assert np.isclose(vy, -2)

您可以更改限制以匹配assert_almost_equal 的行为

【讨论】:

    【解决方案2】:

    NumPy 数组没有定义 __round__。此外,如果数组是 0 维的,并且您将它添加到另一个数字,它可能看起来像一个普通的 Python 对象,但实际上是一个 NumPy 对象。

    >>> scalar = np.array(1.0)
    >>> type(scalar)
    numpy.ndarray
    >>> '__round__' in dir(scalar)
    False
    >>> scalar
    array(1.)
    >>> scalar + 0
    1.0
    >>> type(scalar + 0)
    numpy.float64
    

    您可以使用 NumPy 的测试函数代替 Nose 的,只需对您的代码进行非常小的更改。

    from numpy.testing import assert_equal, assert_almost_equal
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 2021-10-11
      • 2020-12-24
      • 2021-09-02
      • 2022-11-21
      • 2021-08-02
      相关资源
      最近更新 更多