TypeError:只能使用NUMPY将长度为1的数组转换为Python标量 [英] TypeError: only length-1 arrays can be converted to Python scalars with NUMPY

查看:317
本文介绍了TypeError:只能使用NUMPY将长度为1的数组转换为Python标量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# -*- 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:

Running this code gives the following TypeError:

TypeError:只能将长度为1的数组转换为Python标量 在21岁时v =(Q/(((4 * math.pi * e0)(math.sqrt((x * 2 + r0 ** 2)))))

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)))))

推荐答案

使用

Use numpy.sqrt rather than math.sqrt. numpy.sqrt expects a scalar or array as input, on the other hand math.sqrt can only handle scalars.

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

>>> 

这篇关于TypeError:只能使用NUMPY将长度为1的数组转换为Python标量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆