pythoncvxpyconvex-optimization

Minimizing 1/x such that x>=1 and x<=10 using CVXPY


I am trying to solve the following problem using CVXPY:

# Define the variable
x = cp.Variable()

# Define the objective function
objective = cp.Minimize(1/x)

# Define the constraints
constraints = [x >= 1, x <= 10]

# Formulate the problem
problem = cp.Problem(objective, constraints)

# Solve the problem
problem.solve()

# Print the results
print("Optimal value of x:", x.value)
print("Optimal minimum value:", 1/x.value)

It gives me the following error:

DCPError: Problem does not follow DCP rules. Specifically:
The objective is not DCP. Its following subexpressions are not:
1.0 / var8856

Now I know that 1/x is not convex but it is convex in the interval [1, 10] so why does CVXPY raise a DCP error.


Solution

  • This is a good question,

    Here is what I suggest. Always check that the equation you are solving is following DCP Rules. You ask how, You can do that by visiting here. (I have entered '1/x' but you can remove it and check any equation).

    As you can see below, it is classified as Unknown. enter image description here

    Next, you can replace your function with an atomic function, check this link. There are multitude of defined atomic functions that follow DCP rules at the predefined intervals, so always use them(since you will be defining the constraints) Below is the working code.

    # Define the variable
    x = cp.Variable()
    
    # Define the objective function
    objective = cp.Minimize(cp.inv_pos(x))
    
    # Define the constraints
    constraints = [x >= 1, x <= 10]
    
    # Formulate the problem
    problem = cp.Problem(objective, constraints)
    
    # Solve the problem
    problem.solve()
    
    # Print the results
    print("Optimal value of x:", x.value)
    print("Optimal minimum value:", 1/x.value)
    

    Cheers.