diff --git a/bindings/pydrake/symbolic/symbolic_py_monolith.cc b/bindings/pydrake/symbolic/symbolic_py_monolith.cc index 18ffbcab2c24..ee9060964b72 100644 --- a/bindings/pydrake/symbolic/symbolic_py_monolith.cc +++ b/bindings/pydrake/symbolic/symbolic_py_monolith.cc @@ -354,6 +354,8 @@ void DefineSymbolicMonolith(py::module m) { py::arg("env"), doc.Expression.EvaluatePartial.doc) .def("GetVariables", &Expression::GetVariables, doc.Expression.GetVariables.doc) + .def("GetFreeVariables", &Expression::GetFreeVariables, + doc.Expression.GetFreeVariables.doc) .def( "Substitute", [](const Expression& self, const Variable& var, const Expression& e) { diff --git a/bindings/pydrake/symbolic/test/symbolic_test.py b/bindings/pydrake/symbolic/test/symbolic_test.py index 0446a264bf5f..c7e334181e29 100644 --- a/bindings/pydrake/symbolic/test/symbolic_test.py +++ b/bindings/pydrake/symbolic/test/symbolic_test.py @@ -691,6 +691,8 @@ def test_get_variables(self): vars = e_x.GetVariables() self.assertEqual(len(vars), 1) self.assertTrue(list(vars)[0].EqualTo(x)) + vars2 = e_x.GetFreeVariables() + self.assertTrue(vars2.EqualTo(vars)) def test_get_variable_vector(self): vars_ = sym.GetVariableVector([e_x, e_y]) diff --git a/common/symbolic/expression/expression.h b/common/symbolic/expression/expression.h index f785bd9d90fe..df8288e775cf 100644 --- a/common/symbolic/expression/expression.h +++ b/common/symbolic/expression/expression.h @@ -193,6 +193,10 @@ class Expression { /** Collects variables in expression. */ [[nodiscard]] Variables GetVariables() const; + /** Same as GetVariables(); we provide this overload for compatibility with + * Formula. */ + [[nodiscard]] Variables GetFreeVariables() const { return GetVariables(); } + /** Checks structural equality. * * Two expressions e1 and e2 are structurally equal when they have the same diff --git a/common/symbolic/expression/test/expression_test.cc b/common/symbolic/expression/test/expression_test.cc index fca0405009ab..174598ac06ce 100644 --- a/common/symbolic/expression/test/expression_test.cc +++ b/common/symbolic/expression/test/expression_test.cc @@ -1925,13 +1925,14 @@ TEST_F(SymbolicExpressionTest, GetVariables) { EXPECT_FALSE(vars1.include(var_z_)); EXPECT_EQ(vars1.size(), 2u); - const Variables vars2{(x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) + - cosh(y_) + atan2(x_, y_)) - .GetVariables()}; + const Expression e = x_ * x_ * z_ - y_ * abs(x_) * log(x_ + y_) + cosh(x_) + + cosh(y_) + atan2(x_, y_); + const Variables vars2{e.GetVariables()}; EXPECT_TRUE(vars2.include(var_x_)); EXPECT_TRUE(vars2.include(var_y_)); EXPECT_TRUE(vars2.include(var_z_)); EXPECT_EQ(vars2.size(), 3u); + EXPECT_TRUE(e.GetFreeVariables() == vars2); } TEST_F(SymbolicExpressionTest, Swap) {