Skip to main content

Formulating expression to minimize the variance of a list of values in GurobiPy

Awaiting user input



  • Lennart Lahrs
    Gurobi Staff Gurobi Staff

    Hi Koustav,

    I hope the code snippet below helps. Without additional constraints, the variance will always be zero.

    import gurobipy as gp

    model = gp.Model("Minimize Variance")

    n = 10
    x = model.addVars(n, name=f"x")

    mean = x.sum() / n
    variance = gp.quicksum((x[i] - mean) ** 2 for i in range(n))
    model.setObjective(variance / n)

    # TODO: Add other constraints


    Did this answer your question?

  • Koustav Chanda
    First Comment
    First Question

    Hi Lennart,
    While following your direction i am facing this issue

    AttributeError: 'gurobipy.QuadExpr' object has no attribute 'getVar'. Did you mean: 'getVar1'?

    But the code is executing without any error if I remove the square part(**2, though its not the right solution). Can you help me with this?

  • Lennart Lahrs
    Gurobi Staff Gurobi Staff

    Hi Koustav,

    Unfortunately, I was not able to reproduce the error. Can you please share which gurobipy and Python version you are using? Did you already add any other code to the code snippet above? If so, could you please share?


Please sign in to leave a comment.