Skip to main content

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

Awaiting user input

Comments

4 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support.
  • Lennart Lahrs
    • 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

    model.optimize()

    Did this answer your question?

    0
  • Koustav Chanda
    • Gurobi-versary
    • 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?

    0
  • Lennart Lahrs
    • 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?

    0

Post is closed for comments.