Home > OS >  Maximum value of given equation with range of x values
Maximum value of given equation with range of x values

Time:10-03

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

CodePudding user response:

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)

CodePudding user response:

You can save values of Fp in list then find max in list Fp like below.

Try this:

L= range(1, 11)
Fp , Td = [],[]
for idx, x in enumerate(L):
    Fp.append(1000   9*(x**2) - (183)*x)
    Td.append(20 - 0.12*(x**2)   (4.2)*x)
    print(f'x = {x} -> Fp : {Fp[idx]}, Td : {Td[idx]}')
print(f'max in Fp :{max(Fp)}')

Output:

x = 1 -> Fp : 826, Td : 24.08
x = 2 -> Fp : 670, Td : 27.92
x = 3 -> Fp : 532, Td : 31.520000000000003
x = 4 -> Fp : 412, Td : 34.879999999999995
x = 5 -> Fp : 310, Td : 38.0
x = 6 -> Fp : 226, Td : 40.88
x = 7 -> Fp : 160, Td : 43.52
x = 8 -> Fp : 112, Td : 45.92
x = 9 -> Fp : 82, Td : 48.080000000000005
x = 10 -> Fp : 70, Td : 50.0
max in Fp :826

CodePudding user response:

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

CodePudding user response:

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)
  • Related