Popular recipes tagged "dimensions"http://code.activestate.com/recipes/tags/dimensions/popular/2010-07-24T17:24:13-07:00ActiveState Code RecipesNumerical type with units (dimensions.py) (Python)
2010-07-24T17:24:13-07:00David Klaffenbachhttp://code.activestate.com/recipes/users/2007923/http://code.activestate.com/recipes/577333-numerical-type-with-units-dimensionspy/
<p style="color: grey">
Python
recipe 577333
by <a href="/recipes/users/2007923/">David Klaffenbach</a>
(<a href="/recipes/tags/dimensions/">dimensions</a>, <a href="/recipes/tags/numerical/">numerical</a>, <a href="/recipes/tags/units/">units</a>).
</p>
<p>I implemented dimensions.py perhaps eight years ago as an exercise and have used it occasionally ever since.</p>
<p>It allows doing math with dimensioned values in order to automate unit conversions (you can add m/s to mile/hour) and dimensional checking (you can't add m/s to mile/lightyear). It specifically does not convert 212F to 100C but rather will convert 9F to 5C (valid when converting temperature differences).</p>
<p>It is similar to unums (<a href="http://home.scarlet.be/be052320/Unum.html" rel="nofollow">http://home.scarlet.be/be052320/Unum.html</a>) but with a significant difference:</p>
<p>I used a different syntax Q(25,'m/s') as opposed to 100*m/s (I recall not wanting to have all the base SI units directly in the namespace). I'm not entirely sure which approach is really better.</p>
<p>I also had a specific need to have fractional exponents on units, allowing the following:</p>
<pre class="prettyprint"><code>>>> km=Q(10,'N*m/W^(1/2)')
>>> km
Q(10.0, 'kg**0.5*m/s**0.5')
</code></pre>
<p>Looking back I see a few design decisions I might do differently today, but I'll share it anyway.</p>
<p>Some examples are in the source below the line with if __name__ == "__main__":</p>
<p>Note that I've put two files into the code block below, dimensions.py and dimensions.data, so please cut them apart if you want to try it.</p>