只有长度为 1 的数组可以转换为 Python 标量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15449482/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:08:34  来源:igfitidea点击:

only length-1 arrays can be converted to Python scalars

pythonarrays

提问by Bogdan Osyka

Hei I am trying to get a plot for the following problem: U (x) =U0, if |x| ≥ x0 U (x)=U0*|x|/x0 if |x| < x0

嘿,我正在尝试绘制以下问题的图:U (x) = U0, if |x| ≥ x0 U (x)=U0*|x|/x0 如果 |x| < x0

and programm:

和程序:

from pylab import*
x_0=5
U_0=200
#U_x=zeros(n,1)
#x=zeros(n,1)
x=arange(-20,20,0.01)
if float(abs(x))>=x_0:
    U_x=U_0
elif float(abs(x))<x_0:
    U_x=U_0*(float(abs(x))/x_0)
fig=figure()
suptitle("a)") 
fig.subplots_adjust(hspace=0.5)
plot(x,U_x)
xlabel('x [m]')
ylabel('U_x [J]')
show()

But I always get this mistake:

但我总是犯这个错误:

if float(abs(x))>=x_0:
TypeError: only length-1 arrays can be converted to Python scalars

Please help:)

请帮忙:)

采纳答案by HYRY

abs(x) is an array, you can't convert the array to a float value, that is the error. You can write a for loop to do the calculation, but numpy can do vectorized if condition by numpy.where. For more information, read the document:

abs(x) 是一个数组,您不能将数组转换为浮点值,这是错误。您可以编写一个 for 循环来进行计算,但 numpy 可以对 if 条件进行矢量化numpy.where。有关更多信息,请阅读文档

import numpy as np
x = np.arange(-20, 20, 0.01)
x0 = 5
U0 = 200
u = np.where(np.abs(x) >= x0, U0, U0*np.abs(x)/x0)
plot(x, u, lw=3)

output:

输出:

enter image description here

在此处输入图片说明

You can also use piecewisefunction, it can deal with more complicated case.

您也可以使用分段函数,它可以处理更复杂的情况。