^ 不支持的操作数类型:数组上的 'list' 和 'float'

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

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

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

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

我在其他问题上看到,(我认为)我需要使用 for 循环以某种方式 运行 遍历数组中的每个项目,但我不确定该怎么做。代码有几百行,很难分解,所以我只 post 最相关的部分,但它不能单独使用。如果有人需要,很高兴 post 完整代码。澄清一下,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 不支持该操作。 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