【问题标题】:TypeError: only length-1 arrays can be converted to Python scalars with NUMPYTypeError:只有长度为 1 的数组可以用 NUMPY 转换为 Python 标量
【发布时间】:2014-03-03 22:30:58
【问题描述】:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt 
import numpy as np 
import math


#task 2e

x = np.linspace(-0.0001,0.1,50) 

#constants
e0=8.85*10 ** (-12)

r0=3 * 10 ** (-3)
Q=2 * 10** (-9)

Q2=10 * 10*(-9)
r2=5*10**(-3)


v=(Q/((4*math.pi*e0)*(math.sqrt((x**2+r0**2)))))


v2=v+(Q2/((4*math.pi*e0)*(math.sqrt(((x-2)**2+r2**2)))))

plt.plot(x, v)
plt.plot(x, v2)
plt.xlabel("Meter")
plt.ylabel("V1/2(x)")

运行此代码会出现以下类型错误:

TypeError: 只有长度为 1 的数组可以转换为 Python 标量 21 日 v=(Q/((4*math.pi*e0)(math.sqrt((x*2+r0**2)))))

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用numpy.sqrt 而不是math.sqrtnumpy.sqrt 需要标量或数组作为输入,而 math.sqrt 只能处理标量。

    >>> import numpy as np
    >>> import math
    >>> a = np.arange(5)
    >>> np.sqrt(a)
    array([ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ])
    #error
    >>> math.sqrt(a)
    Traceback (most recent call last):
      File "<ipython-input-78-c7d50051514f>", line 1, in <module>
        math.sqrt(a)
    TypeError: only length-1 arrays can be converted to Python scalars
    
    >>> 
    

    【讨论】:

      【解决方案2】:

      使用 np 而不是 ma​​th.sqrt

      v=(Q/((4*math.pi*e0)*(np.sqrt((x**2+r0**2)))))
      
      
      v2=v+(Q2/((4*math.pi*e0)*(np.sqrt(((x-2)**2+r2**2)))))
      

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 2017-07-06
        • 2014-09-27
        • 2013-03-15
        • 1970-01-01
        • 2016-08-06
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多