繁体   English   中英

Python-+不支持的操作数类型:“ numpy.ndarray”和“ str”

[英]Python - unsupported operand type(s) for +: 'numpy.ndarray' and 'str'

长期的读者,但还是第一次海报。 我正在尝试编写一个简单的用户输入的正弦图抽屉,该抽屉会影响图形的频率,幅度和相移。 目的是使一切事物都以圆周率来将数学和物理学生介绍给弧度。

我的问题是,在尝试检测用户输入中是否存在单词“ pi”并将其转换为np.pi以用作浮点数时,出现标题错误。 该程序的代码(除此pi部分以外的其他代码)发布在下面:

import sys
import matplotlib.pyplot as plt
import numpy as np

a = float(input("Amplitude of the curve: "))
f = float(input("Frequency of the curve: "))
p = input("Phase shift of the curve: ")

if "pi" in p:
str.translate(np.pi, "pi")
float(p)

else: float(p)

x = np.linspace(0, 2*np.pi, 1000)
y = a*np.sin((f*x)+p)

plt.grid()

plt.xlabel('x = angle(rads)', fontsize=18)
plt.ylabel('y = amplitude', fontsize=18)
plt.title('The Sine Function', fontsize=26)

plt.xticks(np.linspace(0,2*np.pi,5), ['0', '$\pi$/2', '$\pi$', '3$\pi$/2', '2$\pi$'])
plt.yticks(np.arange(min(y), max(y)+1, max(y)), [round(min(y)), '0', round(max(y))])

plt.plot(x, y)
plt.show()

savefile = input("Do you wish to save the file? ")

if "no" in savefile:
sys.exit()

elif "yes" in savefile:
plt.grid()
plt.xticks(np.linspace(0,2*np.pi,5), ['0', '$\pi$/2', '$\pi$', '3$\pi$/2', '2$\pi$'])
plt.yticks(np.arange(min(y), max(y)+1, max(y)), [round(min(y)), '0', round(max(y))])
plt.plot(x, y)
filename = input("Name the file: ")
plt.savefig(filename, format='pdf', bbox_inches='tight',     pad_inches=0.3)

else: print("\n","Invalid input. Ending Script" ,sep="", end="\n \n")
sys.exit()

提前致谢

您的错误是由于以下行:

y = a*np.sin((f*x)+p)

因此,您不会将p转换为float。 在以下命令中( 同样,您有一个错误的缩进,您需要对其进行更正 ):

if "pi" in p:
    str.translate(np.pi, "pi")
    float(p)

float函数不是,in-place函数需要再次将其分配给p

if "pi" in p:
    str.translate(np.pi, "pi")
    p=float(p)

首先,正如@Kasra指出的那样,

float(p)

不修改对象p 而是返回一个新的float对象。 因此,您需要保存对其返回内容的引用,例如:

p = float(p)

但是, str.translate(np.pi, "pi")并没有您的想法。 实际上,调用此方法时应该出现错误。 translate是一种字符串对象的方法,用于将其他特定字符替换为其他特定字符。 您不能使用它用浮点对象np.pi替换子字符串"pi" ,因为字符串不能包含浮点数。

您想要的可能更像是:

if 'pi' in p:
    p = p.replace('pi', '')
    p = np.pi * float(p)
else:
    p = float(p)

同样,您可以通过挂在图形对象上并保存它而不是创建新图形来简化matplotlib部分。

例如(我正在运行python 2.x,所以我做了一些小的更改。唯一的区别是raw_input vs inputfrom __future__ import print_function 。):

from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np

a = float(raw_input("Amplitude of the curve: "))
f = float(raw_input("Frequency of the curve: "))
p = raw_input("Phase shift of the curve: ")

if "pi" in p:
    p = np.pi * float(p.replace('pi', ''))
else:
    p = float(p)

x = np.linspace(0, 2*np.pi, 1000)
y = a*np.sin((f*x)+p)

fig, ax = plt.subplots()
ax.grid()
ax.set_xlabel('x = angle(rads)', fontsize=18)
ax.set_ylabel('y = amplitude', fontsize=18)
ax.set_title('The Sine Function', fontsize=26)

ax.set(xticks=np.linspace(0,2*np.pi,5),
       xticklabels=['0', '$\pi$/2', '$\pi$', '3$\pi$/2', '2$\pi$'],
       yticks=np.arange(min(y), max(y)+1, max(y)),
       yticklabels=[round(min(y)), '0', round(max(y))])

ax.plot(x, y)
plt.show()

savefile = raw_input("Do you wish to save the file? ")
if "no" in savefile:
    pass
elif "yes" in savefile:
    fig.savefig('filename.pdf', bbox_inches='tight', pad_inches=0.3)
else:
    print("\nInvalid input. Ending Script\n\n")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM