【问题标题】:unsupported operand type(s) for ^: 'list' and 'float' on an array^ 不支持的操作数类型:数组上的“list”和“float”
【发布时间】:2021-03-05 15:57:05
【问题描述】:

问题:(底部的解决方案)

我有一个数据数组,我希望绘制一个图表,然后拟合指数衰减模型,加权为 1/uncertainty^2(这里的变量称为 ampserr)。运行代码将生成图形,但不适合模型并生成错误消息:

unsupported operand type(s) for ^: 'list' and 'float'

我在其他问题上看到,(我认为)我需要使用 for 循环以某种方式遍历数组中的每个项目,但并不确定如何做到这一点。代码有几百行长,很难分解,所以我只发布最相关的部分,但它不会单独工作。如果有人愿意,很高兴发布完整的代码。澄清一下,ampserr 不是整数值。谁能帮我解决这个错误?

代码:

    stderr = result.params['amp'].stderr
    if not stderr:
        stderr = 1e8
    if stderr < stderrThreshold and result.params['amp'] > minimumAmplitude:
        amps.append(result.params['amp'].value) 
        ampserr.append(stderr)
        ts.append((MaestroT*(n+1)-(DeadTime/2)))
    
    ## Plot decay curve & settings for decayplot
    fig, ax = plt.subplots(figsize=(14, 8))
    ax.errorbar(ts, amps, xerr=2, yerr=sqrt(amps), fmt="ko-", capsize = 5, capthick= 2, elinewidth=3, markersize=5)
    plt.xlabel('Time  /s', fontsize=14)
    plt.ylabel('Counts Recorded in the Previous 15 seconds', fontsize=16)
    plt.title("Decay curve of P-31 by $β^+$ emission", fontsize=16)
    

    ## Fit decay curve
    emodel = Model(expdecay)
    
    if rawdata == 1:
        print(ampserr)
        print(amps)
        print(ts)
        
    decayresult = emodel.fit(amps, x=ts, weights=(1/(ampserr)^(2))+1e-8), t=150, A=90)
    ax.plot(ts, decayresult.best_fit, 'r-', label='best fit')

按照 Gionni 的建议尝试使用指数运算符:

decayresult = emodel.fit(amps, x=ts, weights=(1/((ampserr)**(2))+1e-8), t=150, A=90)

解决方案:

decayresult = emodel.fit(amps, x=ts, weights=(1/((np.array(ampserr)**(1))+1e-8)), t=150, A=90) 由 Gionni 建议

【问题讨论】:

  • python中的幂运算是**,而不是^
  • 我试过了,但也没有成功。 unsupported operand type(s) for ** or pow(): 'list' and 'int'
  • 2 解决方案:1) 列表理解weights=[(1/(ampserr_el)^(2))+1e-8) for ampserr_el in ampserr] 2) 使用numpy 并将ampserr 转换为np 数组np.array(ampserr),然后您可以在标量和数组之间进行操作。我认为第二种解决方案更好
  • 做到了,谢谢。你想让它成为一个答案,以便我可以标记它以供其他人将来参考吗?由你决定。

标签: python list graph error-handling floating-point


【解决方案1】:

问题在于您试图用数字对列表进行取幂,正如错误所暗示的那样,这不是 python 中支持的操作。 2 种可能的解决方案:

  1. 使用列表理解:

    weights=[(1/(ampserr_el)**(2))+1e-8) for ampserr_el in ampserr]
    
  2. 使用numpy将ampserr转成数组,支持标量求幂:

    ampserr = np.array(ampserr) # now the ** operator will work
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-10
    • 2015-01-12
    • 1970-01-01
    • 2013-05-08
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多