Skip to main content

arithmetic - Should 0 * 5ft be 0 or 0ft?


After playing with the new quantity system in Mathematica 9 for a while, I keep stumbling over this issue:


0 * Quantity[1, "Meters"]

is not the same as


1 * Quantity[0, "Meters"]


The first is dimensionless 0, the second is 0 meters, and a dimensionless quantity can't be added to or converted to a length like meters.


Take e.g. this simplified example:


startPoint = Quantity[1, "Meters"];
endPoint = Quantity[5, "Meters"];
Manipulate[
UnitConvert[a*endPoint + (1 - a)*startPoint, "Inches"], {a, 0, 1}]

The manipulate converts a point along a line to inches. It works for any setting of a, except 0. and 1., where I get UnitConvert[0. + Quantity[1., "Meters"], "Inches"] instead of a proper length. Generally speaking, it seems that any expression that contains a dimensionless subexpression that can be 0 might break somewhere in your Manipulate, Table or Animate. This seems extremely fragile to me.


Is this a bug? Or am I using Quantity wrong? Should I avoid dimensionless expressions completely? Or avoid Quantity inside dynamic code?




Answer



While it would've been nice if the package handled it automatically, it can be fixed with a simple overloading of Quantity:


Unprotect@Quantity;
Quantity /: (0 | 0.) Quantity[_, unit_] := Quantity[0, unit]
Protect@Quantity;

You can add this to your init.m, so that you don't have to define it each time. You can test your examples with this:


0. Quantity[1, "Meters"]
(* 0 m *)


0 Quantity[1, "Meters"]
(* 0 m *)

Comments