Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preserving units for calculations in programming

I was wondering if there are any sweet languages that offer some sort of abstraction for "feet" vs "inches" or "cm" etc. I was considering doing something like the following in Java:

u(56).feet() + u(26).inches()

and be able to get something like

17.7292 meters as the result.

One possible approach is, when making a new value, immediately convert it to a "base" unit, like meters or something, so you can add them easily.

However, I would much rather have the ability to preserve units, so that something like

u(799.95555).feet() - u(76).feet() 

returns

723.95555 feet

and not

243.826452 meters - 23.1648 meters = 220.661652 meters

//220.661652 meters to feet returns 723.955551 feet 

Since this problem seems like it would be really common, is there any framework or even a programming language that exists that handles this elegantly?

I suppose I can just add the units as they are in my methods, adding matching units together and only converting in order to +-*/ [add/subtract/multiply/divide] when they are requested, which is great for adding and subtracting:

//A
{
    this.inches = 36.2;
    this.meters = 1;
}

//total length is 1.91948 m

if I add this to an object B with values

//B
{
    this.inches = 0.8;
    this.meters = 2;
}

//total length is 2.02032 m

and I get a new object that is

{
    this.inches = 37;
    this.meters = 3;
}

//total length is 3.9398 meters

which is totally awesome, I can convert it whenever I want no problem. But operations such as multiplication would fail ...

//A * B = 3.87796383 m^2
{
    this.inches = 28.96;
    this.meters = 2;
}

// ...but multiplying piece-wise and then adding
// gives you 2.01868383 m^2, assuming you make 2m*1m give you 2 m^2.

So all I really wanted to show with that example was that

( A1 + A2 ) * ( Z1 + Z2 ) is not ( A1 * Z1 ) + ( A2 * Z2 )

And I'm pretty sure this means one has to convert to a common unit if they want to multiply or divide.

The example was mostly to discourage the reflexive answer, that you add or subtract them piece-wise before converting at the last moment, since * and / will fail.

tl;dr: Are there any clever ways to preserve units in programming? Are there clever ways to name methods/routines such that it's easy for me to understand what I'm adding and subtracting, etc?

like image 278
sova Avatar asked Nov 30 '10 22:11

sova


1 Answers

I know for a fact there is such a language, although I haven't used it myself.
It's called Frink.

It not only allows you to mix different units for the same dimension but also operate on several different physical measurements. The sample calculations on its site are a fun read. I particular like the Superman bit.

like image 105
Zecc Avatar answered Jan 04 '23 15:01

Zecc