Solving for single variable inequalities python

437 Views Asked by At

I have a simple equation that can easily be solved by hand but I need to solve using python.

Solve for x:

x < 9
x > 4.5
x < 5.6
x > 4.8

So we can easily see x=5 is one of the acceptable solutions. But how would I go about using python to solve for x and return a single value? Thank you.

3

There are 3 best solutions below

1
Abstract On BEST ANSWER

Depending on the decimal precision you need in your answer, you can increase or decrease the step size in arange below. This is a pythonic way of solving the problem using list comprehension:

Example:

import numpy as np

nums = np.arange(0, 6, 0.1)
answers = [x for x in nums if x < 9 and x > 4.5 and x < 5.6 and x > 4.8]

print(answers)

Output:

[4.800000000000001, 4.9, 5.0, 5.1000000000000005, 5.2, 5.300000000000001, 5.4, 5.5]

If you only care about integer answers, use an integer step size:

import numpy as np

nums = np.arange(0, 6, 1)
answers = [x for x in nums if x < 9 and x > 4.5 and x < 5.6 and x > 4.8]

print(answers)

Output:

[5]
0
k_o_ On

You can use SciPy linprog to get a generic solution.

They are also giving an example at the bottom. This is the Python code:

c = [1]
A = [[1], [-1], [1], [-1]]
b = [9, -4.5, 5.6, -4.8]
x0_bounds = (-4.5, 9)
from scipy.optimize import linprog
res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds])

print(res)

Printing 4.8 as the minimal solution, in your case > 4.8.

0
function-hack On

Set a minimum and maximum value (initially to None). Then iterate through the inequalities, updating them if their range has changed:

min_val = None
max_val = None
ineqs = (('<', 9), ('>', 4.5), ('<', 5.6), ('>', 4.8))

for i in ineqs:
    if i[0] == '<':
        # Smaller than:
        if max_val is None:
            max_val = i[1]
        else:
            max_val = min(max_val, i[1])
    elif i[0] == '>':
        # Greater than
        if min_val is None:
            min_val = i[1]
        else:
            min_val = max(min_val, i[1])

print(f'The value is between {min_val} and {max_val}')