Is there a way to use FindMinimum with quantities? For example:

FindMinimum[{Quantity[x, "cm"] + Quantity[y, "m"], 
  x >= Quantity[0, "cm"], y >= Quantity[0, "cm"]}, {x, y}]

but this throws an error. Any ideas?

Edit: I see now that this code is inconsistent (treating x as a unitless variable in the objective, but as a quantity with units in the inequality constrains, see answers). But here is another example that also came up in my code and does not work. I think this is consistent.

FindMinimum[{y/(x + y), 
             x >= Quantity[1, "m"], y >= Quantity[2, "m"]}, 
             {{x, Quantity[1, "m"]}, {y, Quantity[2, "m"]}}]
  • $\begingroup$ Seems to work if you don't use units, and then only apply them to the results. $\endgroup$
    – ktm
    Oct 3, 2017 at 19:49
  • $\begingroup$ @user6014 Not an option. This is only a minimal example, but in my application I have many routines interconnected, and getting rid of units entirely would require a major rewrite. Moreover, if I can't do this, then units in Mathematica are basically useless. $\endgroup$
    – a06e
    Oct 3, 2017 at 23:10
  • $\begingroup$ @becko You should be able to eliminate units only in the expression passed to FindMinimum and to put them back in on the result. No need to eliminate them throughout the rest of the application. $\endgroup$
    – masterxilo
    Oct 3, 2017 at 23:23
  • $\begingroup$ @masterxilo Yes, that is Bob Hanlon's below, which the currently accepted answer. $\endgroup$
    – a06e
    Oct 3, 2017 at 23:32
  • $\begingroup$ "Mathematica are basically useless" .. sorry to say but that is my conclusion, don't try to incorporate the units functionality with serious programing tasks. $\endgroup$
    – george2079
    Oct 4, 2017 at 0:11

2 Answers 2


Using brute force

   {Quantity[x, "cm"] + Quantity[y, "m"],
     x >= Quantity[0, "cm"], y >= Quantity[0, "cm"]} /. 
    z_Quantity :> (dim = QuantityUnit[UnitConvert[z]];
      QuantityMagnitude[UnitConvert[z]]), {x, y}] // 
  ReplacePart[#, 1 -> Quantity[#[[1]], dim]] &]

(* {Quantity[0., "Meters"], {x -> 0., y -> 0.}} *)

You use x as a pure number (e.g., Quantity[x, "cm"]) and as a Quantity object (e.g., x>=Quantity[0, "cm"]). Avoid this with:

    {Quantity[x, "cm"] + Quantity[y, "m"], x >= 0, y >= 0},
    {{x, 1}, {y, 1}}

{Quantity[0., "Meters"], {x -> 0., y -> 0.}}

  • $\begingroup$ You are right, I see my code was inconsitent. $\endgroup$
    – a06e
    Oct 3, 2017 at 20:44
  • $\begingroup$ There more complex examples where this approach does not work. Please see the edit to my question. $\endgroup$
    – a06e
    Oct 3, 2017 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.