Home > Software engineering >  I don't understand why Python raises the error 'TypeError: bad operand type for unary -: &
I don't understand why Python raises the error 'TypeError: bad operand type for unary -: &

Time:11-23

I am currently using a method that I used to use before in many other scripts. This method uses linspace function from numpy and we apply another function (in this case decrease) in order to make a plot. I added the function implement, which is not essential, to correct some other errors I got. I did the same for the conversion of t from ndarray into list. Usually, I don't convert the ndarray from linspace into a list, I can apply it directly into a function and get an other ndarray of results. This is a really simple script but I can't figure out why python is raising me this error. Here's the script. Thanks in advance for your help.

import matplotlib.pyplot as plt
from math import *
import numpy as np


def decrease(a,k,t):
    res = (a*exp(-k*t)   1 - a)
    return(res)

t = np.linspace(0,365,10000)
t = t.tolist()

def implement(a,k,t):
    k = []
    for i in t:
        k.append(decrease(a,k,i))
    return(k)

prop_red_LC = implement(0.43184,0.002460075,t)
prop_red_LT = implement(0.4477958,0.002515857,t)
prop_red_GC = implement(0.383793,0.002467542,t)
prop_red_GT = implement(0.3603323,0.00315626,t)


axes = plt.axes()
axes.grid() # dessiner une grille pour une meilleur lisibilité du graphe
plt.plot(t, prop_red_LC,label="Simulation de la décomposition pour AlpineControl", c='r')
plt.xlabel("temps (jours)")
plt.ylabel("M(t)/M0")
plt.legend()
plt.show()

Traceback (most recent call last):

  File "<ipython-input-61-5b6414ac720a>", line 1, in <module>
    prop_red_LC = implement(0.43184,0.002460075,t)

  File "<ipython-input-60-6ce6b9f5c45a>", line 16, in implement
    k.append(decrease(a,k,i))

  File "<ipython-input-60-6ce6b9f5c45a>", line 7, in decrease
    res = (a*exp(-k*t)   1 - a)

TypeError: bad operand type for unary -: 'list'

CodePudding user response:

The program confused your list with the k value, change the name of your list variable and it will work.

def implement(a,k,t):
    l = []
    for i in t:
        l.append(decrease(a,k,i))
    return l
  • Related