【问题标题】:Python -> TypeError: unsupported operand type(s) for ^Python -> TypeError: ^ 不支持的操作数类型
【发布时间】:2018-04-27 12:01:04
【问题描述】:

我正在为 Python 代码而苦苦挣扎。我想这样做equation

这是我的代码:

fs= 5000
T=np.linspace(0,2.2,fs)
n=np.arange(fs*2.2)
u=[]
for x in T:
    if x < 0.2:
        u.append(x * np.sin(34*np.pi*n/fs))
    if (x >= 0.2 and x < 0.8):
        u.append(1/x * np.log10(x+1))
    if x >= 0.8 and x < 1.4:
        u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))
    if x >= 1.4:
        u.append(np.sin(20*np.pi*n/fs + x/3))

而python返回:

  File "D:/Semestr V/Podstawy Transmisji Danych/labki-ZAD3.py", line 20, in <module>
    u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))

TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'int'

【问题讨论】:

标签: python algorithm list numpy equation


【解决方案1】:

除了错误^/**,最好的方法是使用np.piecewise,它旨在快速获得矢量结果:

fs= 5000
x=np.linspace(0,2.2,fs)
n=3

functions=[ 
lambda x : x * np.sin(34*np.pi*n/fs), 
lambda x : 1/x * np.log10(x+1),
lambda x : (x**2 + 1) * np.sin(12*np.pi*n/fs),
lambda x : np.sin(20*np.pi*n/fs + x/3)]

conditions=[x < 0.2,(x >= 0.2) & (x < 0.8), (x >= 0.8) & (x < 1.4), x >= 1.4]

res=np.piecewise(x,conditions,functions)
plt.plot(x,res)

只需循环 n 即可获取所有值。

【讨论】:

    【解决方案2】:

    幂运算符是**^ 是按位异或。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2011-03-08
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多