473,387 Members | 1,583 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Units of measurement

I'm sure this has been done before, but it just struck my fancy, an
example of Python's "emulating numeric types", inspired by the old
Unix "units" utility, and the Frink language. The language reference
for these features is somewhat unclear and I'll enter some sourceforge
items. Maybe I'll write a calculator-with-units around it. If I were
really industrious, I'd attempt a Frink-like interpreter, but don't
hold your breath.

================================================== ==============

try:
set
except NameError:
from sets import Set as set # python 2.3 ...

class Unit:
def __init__(self, coef, dimensions):
self.dimensions = dimensions
self.coef = coef
def __add__(self, other):
if self.dimensions != other.dimensions:
raise TypeError, ('dimension mismatch', self, other)
return Unit(self.coef + other.coef, self.dimensions)
def __sub__(self,other):
return self + (-1.0) * other
def __rmul__(self, x):
return x*self
def __rdiv__(self, x):
return x/self
def __mul__(self, other):
pc = self.coef * other.coef
sd, od = self.dimensions, other.dimensions
basis = set(sd.keys()) | set(od.keys())
pa = [(d, sd.get(d,0)+od.get(d,0)) for d in basis]
pd = dict([(d,a) for d,a in pa if a != 0])
return Unit(pc, pd)
def __repr__(self):
a = [repr(self.coef)]
for d,c in self.dimensions.iteritems():
s = str(d)
if c != 1: s += '^'+str(c)
a.append(s)
return '*'.join(a)
def __div__(self, other):
od = other.dimensions
inv = Unit(1.0 / other.coef,
dict([(d, -od[d]) for d in od]))
return self * inv
def __pow__(self, n):
n = n.coef
if self.dimensions and type(n) not in (int,long):
raise TypeError, ('exponent must be integer', self,n)
cn = self.coef ** n
sd = self.dimensions
return Unit(self.coef ** n,
dict([(d,sd[d]*n) for d in sd]))

def __coerce__(self, other):
if isinstance(other, Unit): return self, other
return self, Unit(other, {})

def __float__(self):
if self.dimensions:
raise TypeError, ('unit must be dimensionless for float cast', self)
return float(self.coef)
def __int__(self):
return int(float(self))

def base_unit(name):
return Unit(1.0, {name : 1})

meter = base_unit('m')
second = base_unit('s')
kg = base_unit('kg')
coulomb = base_unit('coulomb')

centimeter = meter / 100
inch = 2.54 * centimeter
foot = ft = 12 * inch
mile = 5280*foot
minute=60*second
hour=60*minute
speed_limit = 55 * mile / hour
furlong = mile / 8
day = 24 * hour
fortnight = 14 * day
# could include more units but you get the idea

c = 186282*mile/second
print 'speed of light =', c/(furlong/fortnight), 'furlongs per fortnight'
# ...
Jan 17 '07 #1
4 2612
Paul Rubin wrote:
I'm sure this has been done before, but it just struck my fancy, an
example of Python's "emulating numeric types", inspired by the old
Unix "units" utility, and the Frink language.
Oh yeah, it's been done before. Several times over, in fact.

Unum
http://home.tiscali.be/be052320/Unum.html

Caltech's pyre.units
http://www.cacr.caltech.edu/projects/pyre/

Konrad Hinsen's Scientific.Physics.PhysicalQuantity
http://dirac.cnrs-orleans.fr/ScientificPython/

Will Ware posted one to the list.
http://groups.google.com/group/comp....05aea353c1563d

And there was another one announced here sometime in the past year or so, IIRC,
but I don't recall the name of it or that of the author. :-(

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jan 17 '07 #2
Robert Kern wrote:
Paul Rubin wrote:
I'm sure this has been done before, but it just struck my fancy, an
example of Python's "emulating numeric types", inspired by the old
Unix "units" utility, and the Frink language.

Oh yeah, it's been done before. Several times over, in fact.
<cut>
And there was another one announced here sometime in the past year or so, IIRC,
but I don't recall the name of it or that of the author. :-(
Perhaps you are referring to the scalar class at
http://RussP.us/scalar.htm

The nice thing about this one (which I wrote myself) is that after you
do your development and are ready for "production" runs, you can easily
disable the unit checks and get the efficiency of built-in numeric
types. That can be two orders of magnitude faster!

It comes with a complete user manual too (pdf and html). I'm using it
for my engineering work, and it's working great!

Jan 18 '07 #3
Russ wrote:
Robert Kern wrote:
>And there was another one announced here sometime in the past year or so, IIRC,
but I don't recall the name of it or that of the author. :-(

Perhaps you are referring to the scalar class at
http://RussP.us/scalar.htm
Yup, you're the one.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jan 18 '07 #4
Paul Rubin <http://ph****@NOSPAM.invalidwrote:
>
I'm sure this has been done before, but it just struck my fancy, an
example of Python's "emulating numeric types", inspired by the old
Unix "units" utility, and the Frink language.
...
# could include more units but you get the idea
...
c = 186282*mile/second
print 'speed of light =', c/(furlong/fortnight), 'furlongs per fortnight'
# ...
I could not skip to the next message without cutting, pasting, and
executing that script to find out what the speed of light actually was in
furlongs per fortnight.

Now I need to figure out how to work that into a cocktail party
conversation. "Hey, the deficit isn't the only thing that is approaching
1.8 trillion..."
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jan 19 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: Peter Mount | last post by:
Hello I've started using CSS more in the last couple of weeks and in the last week I've started using em units. Are there any rulers I download that can show measurements in em units or is there...
0
by: Alex Vinokur | last post by:
=================================== ------------- Sorting ------------- Comparative performance measurement =================================== Testsuite : Comparing Function Objects to...
7
by: Chris Mahoney | last post by:
Hi Is it possible for a VB 2003 app to determine the appropriate measurement units for the user's location? For example, I would like to make my app default to using miles if the user is in the...
38
by: axlq | last post by:
I'm trying to figure out how to display a box that has a width in "em" units. So far no luck. Below is some HTML that displays two rows of 30 'm' characters in lowercase and uppercase, followed...
2
by: TheSeeker | last post by:
Hi, As part of a larger project, I am trying to use the GNU Units program to provide unit conversions between quantities. My first iteration, which worked OK, was to simply use units as a...
3
by: Jack Russell | last post by:
How can I find out what the current measurement units (US or metric) setting is (Control panel, regional settings, advanced). I can get things like the decimal separator but cannot find this one ...
4
by: beatdream | last post by:
I am designing a database to handle different kinds of products ... and these products can have different properties...for example, a trouser can be specified by the width, length, color, and other...
18
by: kwikius | last post by:
Well lads :-)... looking at your Boost Units library the impression I get is that you got your library into boost Before writing anything much apart from some documentation, which was AFAICS even...
3
by: kr151080 | last post by:
I need some help with a Measurement Program I Wrote.....I have this code as the main workings of my program: import java.util.*; public class Measurement{ { static Scanner console = new...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.