这是代码:
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)
答案 0 :(得分:0)
这些变量不是浮点数,而是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
的行为
答案 1 :(得分:0)
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