[Tutor] Convert doesn't work... I'm stumped

Jacob S. keridee at jayco.net
Wed Mar 16 04:49:41 CET 2005


Okay, not a very descriptive subject, but here goes...

This is the code

###########################################
from decimal import Decimal as D
"""Everything is first converted to meters, and then converted to the unit
you want to extend usage.

dic[unit] = (unittometers,meterstounit)
"""

dic = {## Metric ##
       'm':(lambda x:x,lambda x:x),
       'km':(lambda x:1000*x,lambda x:x/1000),
       'cm':(lambda x:x/100,lambda x:100*x),
       'mm':(lambda x:x/1000,lambda x:1000*x),

       ## English ##
       'in':(lambda x:127*x/5000,lambda x:5000/(127*x)),
       'ft':(lambda x:381*x/1250,lambda x:1250/(381*x)),
       'mi':(lambda x:201168*x/125,lambda x:125/(201168*x)),
       'yd':(lambda x:1143*x/1250,lambda x:1250/(1143*x))
       }

def convert(num,unit1,unit2):
    num = D(str(num))
    tometer = dic[unit1][0](num)
    frommeter = dic[unit2][1](tometer)
    return frommeter
####################################################

Fortunately my docstrings are getting slightly better, and you can at least 
tell that
the function "convert" first changes the value to meters then to the second 
unit.
This increases the number of conversions I can do to N! where N is the 
number of
known units, I'm guessing...

But, I digress--to the problem...
If I call convert(3,'ft','yd'), I should get Decimal("1")
instead, I get Decimal("1.195990046301080256481500617")

The first lambda function returns the number converted to meters, the second 
lambda function converts the number to the unit you want.
So, expanded -- convert is

def convert(num, unit1, unit2):
    num = D(str(num))
    tometer = dic[unit1][0]      # a function that converts its argument to 
meters
    frommeter = dic[unit2][1]   # a function that converts its argument from 
meters to the unit you want
    inmeters = tometer(num)
    in_the_units = frommeter(inmeters)
    return in_the_units

I have checked all of the lambdas I have defined...

                               x -ft-     12 -in-        2.54 -cm-         m
def dic['ft'][0](x) =  ----  X --------   X  -----------  X -------        = 
12*2.54*x/100  = 12*254*x/10000  =  381*x/1250
                                            -ft-                -in- 
100 -cm-

Like that of above...

I just don't get where it goes from *okay* to 0.195990046301... margin 
error.

Can anyone help?

Jacob 



More information about the Tutor mailing list