Reputation: 214
I am trying to find out the maximum value of a function (here it is T(n)) through this code:
for i in range(2, imax-1):
Q=q(i-1)-q(i)
Tn=T(i)+(Dt/(rho*cp*0.1))*Q
y=max(Tn)
But I am getting an error "float' object is not iterable". Any suggestion on this would be helpful to me.
Please note that, "q" and "T(i)" have been defined as functions of "i", and all the other terms are constants.
Upvotes: 0
Views: 2584
Reputation: 6526
The max
function returns the maximum values among several ones, so you logically need to pass at least 2 values as parameters, inside a list or a tuple for example.
I suggest you this solution based on your current code to be easily understood:
y = None
for i in range(2, imax-1):
Q=q(i-1)-q(i)
Tn=T(i)+(Dt/(rho*cp*0.1))*Q
if y is None:
y=Tn
else:
y=max(Tn,y)
To go further (and maybe better), list comprehension is well adapted in this case, as detailed by Andrea in his answer.
Upvotes: 2
Reputation: 1240
max
takes an iterable (e.g. a list
, dict
, str
, etc), so it might look something like, max([1, 2, 3]) #=> 3
. A common pattern is to use a comprehension: max(f(x) for x in range(10))
. The thing about comprehensions is that they require a single expression, so you can't use the original definition of Tn
.
If you expand the definition of Tn
so that it's a single expression, we get Tn = T(i) + (Dt/(rho*cp*0.1)) * (q(i-1) - q(1))
. Use that in the comprehension and we get max(T(i) + (Dt/(rho*cp*0.1)) * (q(i-1) - q(1)) for i in range(2, imax-1))
.
Upvotes: 1