【问题标题】:Random numbers- only length-1 arrays can be converted to Python scalars随机数 - 只有长度为 1 的数组可以转换为 Python 标量
【发布时间】:2017-01-25 03:58:55
【问题描述】:
from math import sin, cos, pi
import numpy as np
N=10

a=np.random.randint(0, 360+1, N)
print (a)

theta=a*pi/180
print(theta)

x=[cos(theta)]
print(x)
y=[sin(theta)]
print(y)

TypeError                                 Traceback (most recent call last)
<ipython-input-47-632b45c2aba1> in <module>()
      9 theta=a*pi/180
     10 print(theta)
---> 11 x=[cos(theta)]
     12 print(x)
     13 y=[sin(theta)]

TypeError: only length-1 arrays can be converted to Python scalars

【问题讨论】:

  • 请用代码块格式化您的代码
  • 问题是什么?

标签: python arrays numpy random polar-coordinates


【解决方案1】:

尝试使用np.cos(theta) 而不是cos(theta)sin 也是如此。

只有 NumPy 函数可以同时应用于标量和数组。常规的 cos()sin() 只需要标量参数,并且在示例中失败,因为您尝试将它们应用于大小为 10 的 NumPy 数组。

NumPy cos 文档:http://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html cos 文档:https://docs.python.org/2/library/math.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2016-03-10
    • 2015-02-16
    相关资源
    最近更新 更多