类型错误:只能使用 NUMPY 将长度为 1 的数组转换为 Python 标量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22158922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: only length-1 arrays can be converted to Python scalars with NUMPY
提问by user3376799
# -*- 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)")
Running this code gives the following TypeError:
运行此代码会产生以下类型错误:
TypeError: only length-1 arrays can be converted to Python scalars On 21 v=(Q/((4*math.pi*e0)(math.sqrt((x*2+r0**2)))))
类型错误:只有长度为 1 的数组可以转换为 Python 标量 On 21 v=(Q/((4*math.pi*e0) (math.sqrt((x*2+r0**2)))))
采纳答案by Ashwini Chaudhary
Use numpy.sqrtrather than math.sqrt. numpy.sqrtexpects a scalar or array as input, on the other hand math.sqrtcan only handle scalars.
使用numpy.sqrt而不是math.sqrt. numpy.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
>>>
回答by ThePredator
use npinstead of math.sqrt
使用np代替math.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)))))

