【问题标题】:TypeError: 'float' object cannot be interpreted as an integer as numpy randon.randn python [duplicate]TypeError:'float'对象不能解释为numpy randon.randn python的整数[重复]
【发布时间】:2018-04-02 17:18:27
【问题描述】:

在这段代码中

N = 4
M = 30

# Generar datos a partir de 3 clusters diferentes:

X1 = 10 + 2*np.random.randn(M/3,N)
X2 = -10 + 5*np.random.randn(M/3,N) 
X3 = 1*np.random.randn(M/3,N) 

我收到此错误

Traceback (most recent call last):
  File "/home/user/PycharmProjects/tema3/3.18_MDS.py", line 16, in <module>
    X1 = 10 + 2*int(np.random.randn(M/3,N)) # cluster 1 (dispersion media)
  File "mtrand.pyx", line 1420, in mtrand.RandomState.randn
  File "mtrand.pyx", line 1550, in mtrand.RandomState.standard_normal
  File "mtrand.pyx", line 167, in mtrand.cont0_array
TypeError: 'float' object cannot be interpreted as an integer

我不确定这个问题,因为我认为我没有将任何浮点数传递给 randn。

【问题讨论】:

  • python3 我猜?尝试查看print(M/3)的输出
  • 是的,它是 python3
  • python 3 中的整数除法返回一个浮点数。如果你想截断(就像 python2 那样)你需要使用//。尝试在任何地方用M//3 替换M/3
  • 尽管这是一个骗局,并且 OP 应该 已经尝试使用一些打印语句来调试程序,但我认为这里的反对意见有点苛刻。 / 操作符的行为变化并不明显。
  • @pault 问题不是/ 的行为变化,而是numpy 不接受30/3 = 10.0 作为整数(即​​使它是整数)

标签: python python-3.x numpy


【解决方案1】:

在 Python3 中,/ 的整数除法返回一个浮点数。您需要使用// 来获取整数(向下舍入)。

>>> type(1)
<class 'int'>

>>> type(1/1)
<class 'float'>

>>> type(1//1)
<class 'int'>

>>> 1/2
0.5

>>> 1//2
0

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多