0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Laurent
1

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)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.