gpt4 book ai didi

python - 类型错误 : only length-1 arrays can be converted to Python scalars with NUMPY

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:26 25 4
gpt4 key购买 nike

# -*- 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: only length-1 arrays can be converted to Python scalars On 21 v=(Q/((4*math.pi*e0)(math.sqrt((x*2+r0**2)))))

最佳答案

使用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

>>>

关于python - 类型错误 : only length-1 arrays can be converted to Python scalars with NUMPY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22158922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com