Sunny Start
Sunny Start

Reputation: 11

Maximum value of given equation with range of x values

How can I find the maximum value of the following equation: Fp=(1000 + 9*(x**2) - (183)*x) Given values of x in the range of (1-10), using python. This is what I have tried already:

L= range(1, 11)
for x in L:
    Fp=(1000 + 9*(x**2) - (183)*x)
    Td=20 - 0.12*(x**2) + (4.2)*x
    print(Fp, Td)
    print(max(Fp))

Upvotes: 1

Views: 488

Answers (3)

ATony
ATony

Reputation: 703

The problem with your code is that you're taking the max of a scalar rather than of the values of Fp for each of the values of x.

For a small range of integer values of x, you can iterate over them as you do. And, if you only need the max value,

L = range(1, 11)
highest_Fp = 0    # ensured lower than any Fp value
for x in L:
    Fp = (1000 + 9*(x**2) - (183)*x)
    Td = 20 - 0.12*(x**2) + (4.2)*x
    print(Fp, Td)
    if Fp > highest_Fp:
        highest_Fp = Fp
print(highest_Fp)

Upvotes: 1

ARK1375
ARK1375

Reputation: 828

Assuming that you have the set of natural numbers in mind, since you have a small range of numbers to check (only 10 numbers), the first approach would be to check the value of the equation for every number, save it in a list, and find the maximum of that list. Take a look at the code below.

max_list = []
for x in range(1,11):
    Fp = (1000 + 9*(x**2) - (183)*x)
    max_list.append(Fp)

print( max(max_list) )

Another more elegant approach is to analyze the equation. Since your Fp equation is a polynomial equation with the positive second power coeficent, you can assume that either the last element of the range is going to yield the maximum or the first.
So you only need to check those values.

value_range = (1,10)
Fp_first = 1000 + 9*(value_range[0]**2) - (183)*value_range[0]
Fp_last = 1000 + 9*(value_range[1]**2) - (183)*value_range[1]
max_val = max(Fp_first , Fp_last)

Upvotes: 2

user2668284
user2668284

Reputation:

You could do it like this:-

def func(x):
    return 1_000 + 9 * x * x - 183 * x

print(max([func(x) for x in range(1, 11)]))

Upvotes: 1

Related Questions