I am surprised that there are some cases where unit conversion works, even if the input- and output dimensions are clearly different:
UnitConvert[Quantity[1., 1/"Meters"], "Centimeters"]
(* returns 0.01/cm *)
Also, the following (and many, more complicated inputs) work. It seems that when you have a compound unit at the input, and a single unit for the output, Mathematica only converts the specified "dimension" (length, time, ...) and any power of that dimension (length^n, ...):
UnitConvert[Quantity[1., "Amperes"/"Meters"], "Centimters"]
(* returns 0.01 A/cm *)
UnitConvert[Quantity[1., "Meters"*"Kilograms"/"Amperes"], "Pounds"]
(* returns 2.20462 lb m/A *)
UnitConvert[Quantity[1., "Meters"*"Feet"*"Kilograms"/"Amperes"], "Centimeters"]
(* returns 3048 kg cm^2/A *)
While this is a convenient shortcut to simplify compound units, it also seems dangerous, since this behaviour is not specified in the documentation.
Also, I am using units in my calculations to ensure I am not making trivial errors in entering formulas or input values. I need Mathematica to throw an error when it encounters such incompatible unit conversions.
Is this a feature (to be specified as such in future versions) or a bug (likely to be fixed in future versions)? And is there perhaps a way to specify a "strict" behaviour for UnitConvert?
Answer
No idea concerning the interesting behaviour you mention about UnitConvert. However here is a simple workaround for you strict conversion problem (using the function CompatibleUnitQ suited for your need !!)
strictUnitConvert[q1_, q2_] := UnitConvert[q1, q2] /; CompatibleUnitQ[q1, q2];
strictUnitConvert[_, _] := "Error !! Not compatible Units";
Test
strictUnitConvert[Quantity[1., 1/"Meters"], "Centimeters"]
strictUnitConvert[Quantity[1., "Amperes"/"Meters"], "Centimeters"]
strictUnitConvert[Quantity[1., "Meters"*"Kilograms"/"Amperes"], "Pounds"]
strictUnitConvert[Quantity[1., "Meters"*"Feet"*"Kilograms"/"Amperes"], "Centimeters"]
all return
Error !! Not compatible Units
whereas for example :
strictUnitConvert[Quantity[1., "Meters"/"Seconds"], "Centimeters"/"Minutes"]
return
Quantity[6000., ("Centimeters")/("Minutes")]
Comments
Post a Comment