0

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.

1
  • Implement the logic for solving the system of inequalities. Can you describe the logic you are using when you solve it by hand? Then implement that in Python Commented Jul 20, 2021 at 20:11

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this simple and easy solution
1

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

Comments

1

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.

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.