TypeError:ufunc'splaly'不包含带签名匹配类型的循环dtype('S32')dtype('S32')dtype('S32')

A. *_*son 16 python matplotlib typeerror

我是编码的新手,但我正在尝试创建一个非常简单的程序,它基本上会绘制一条线.用户将输入v和a然后v的值,a和x将确定y.我试图这样做:

x = np.linspace(0., 9., 10)
a = raw_input('Acceleration =')
v = raw_input('Velocity = ')
y=v*x-0.5*a*x**2.
Run Code Online (Sandbox Code Playgroud)

基本上这将代表抛物线,其中v是速度,a是加速度,x是时间.但是,我一直收到这个错误:

TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('S32'
) dtype('S32') dtype('S32')
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 11

来自以下文件raw_input:

然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行.

所以会发生的是你尝试将一个字符串与一个浮点数相乘,就像y="3" * x - 0.5 * "3" *x**2没有定义的那样.

避免这种情况的最简单方法是首先将输入字符串转换为float.

x = np.linspace(0., 9., 10)
a = float(raw_input('Acceleration ='))
v = float(raw_input('Velocity = '))
y=v*x-0.5*a*x**2
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用的是python 3,则需要使用input而不是raw_input,

a = float(input('Acceleration ='))
Run Code Online (Sandbox Code Playgroud)


小智 6

我最近遇到了这个问题,通过执行以下操作将 x 的 dtype 更改为特定的内容:

x = np.asarray(x, dtype='float64')
Run Code Online (Sandbox Code Playgroud)