简体   繁体   中英

type numpy.ndarray doesn't define __round__ method

this is the code:

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

Checked against the following:

 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) 
 '''

The error message, which I don't understand:

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

Those variables are not floats, they are numpy types. Numpy types don't implement the .__round__() method which is why you are getting the error. These types have their own .round() method which is what numpy uses. Can you swap to:

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

You can change the limits to match the behavior of assert_almost_equal

NumPy arrays do not define __round__ . Additionally if the array is 0 dimensional, and you add it to another number, it may look like a regular Python object but is actually a NumPy object.

>>> 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

You can use NumPy's testing functions instead of Nose's with a very small change to your code.

from numpy.testing import assert_equal, assert_almost_equal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM