只有长度为1的数组才能转换为Python标量

时间:2022-05-31 12:17:06

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)=情况,如果x | |≥x0 U(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:)

请帮助:)

1 个解决方案

#1


8  

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可以通过numpi .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:

输出:

只有长度为1的数组才能转换为Python标量

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

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

#1


8  

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可以通过numpi .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:

输出:

只有长度为1的数组才能转换为Python标量

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

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