pythonoptimizationscipyminimizationnonlinear-functions

Optimizing input where output has constraints in python


I trying to minimise an input ( 1 variable ) to a non linear function where the output is a probability.

As in, if the input is 5 the output probability is 40% , 10 input the probability becomes say 93%. The function to compute the probability is deterministic.

Now i want to minimise the input such that the probability is greater than say 80% . Is there a simple way of doing this in python using scipy library ?


Solution

  • Does the following help?

    import math
    from scipy.optimize import minimize,NonlinearConstraint
    
    def fmin(x):
    # this is the function you are minimizing
    # in your case this function just returns x
        return x
    
    def fprob(x):
    # this is the function defining your probability as a function of x
    # this function is maximized at x=3, and its max value is 1
      return math.exp(-(x-3)*(x-3))
    
    # these are your nonlinear constraints
    # since you want to find input such that your probability is > 0.8
    # the lower limit is 0.8. Since probabilty cannot be >1, upper limit is 1
    nlc  = NonlinearConstraint(fprob,0.8,1)
    
    # the zero is your initial guess
    res = minimize(fmin,0,method='SLSQP',constraints=nlc)
    
    # this is your answer
    print(f'{res.x=}')