diff --git a/ilpy/impl/solvers/Objective.cpp b/ilpy/impl/solvers/Objective.cpp index 308bbc2..5d975ec 100644 --- a/ilpy/impl/solvers/Objective.cpp +++ b/ilpy/impl/solvers/Objective.cpp @@ -37,6 +37,11 @@ Objective::getCoefficients() const { void Objective::setQuadraticCoefficient(unsigned int varNum1, unsigned int varNum2, double coef) { + if (varNum1 >= size()) + resize(varNum1 + 1); + if (varNum2 >= size()) + resize(varNum2 + 1); + if (coef == 0) { _quadraticCoefs.erase(std::make_pair(varNum1, varNum2)); diff --git a/tests/test_objective.py b/tests/test_objective.py new file mode 100644 index 0000000..e2b906a --- /dev/null +++ b/tests/test_objective.py @@ -0,0 +1,16 @@ +import ilpy + + +def test_resize() -> None: + obj = ilpy.Objective() + assert len(obj) == 0 + + obj.set_coefficient(0, 2) # linear term (2x) + assert len(obj) == 1 + + obj.set_quadratic_coefficient(1, 1, 3) # quadratic term (3y^2) + assert len(obj) == 2 + + obj2 = ilpy.Objective() + obj2.set_quadratic_coefficient(0, 0, 1) # quadratic term (x^2) + assert len(obj2) == 1