[Tutor] Need a better name for this function

Dave Angel davea at ieee.org
Wed Dec 16 00:05:33 CET 2009


Richard D. Moores wrote:
> def float_to_exact_number_stored_in_computer(f):
>    """
>    Given a float, return the exact number stored in computer.
>
>    See
> http://docs.python.org/3.1/tutorial/floatingpoint.html#representation-error
>    """
>    from decimal import Decimal
>    return Decimal.from_float(f)
>
> I've just borrowed from the doc, but that name is too long, isn't it? Please
> suggest something shorter but still meaningful.
>
> Thanks,
>
> Dick Moores
>
>   
As Hugo says, when your entire function consists of a single call to 
another one, you can usually simplify it.  In this case, something like:

import decimal
float_to_decimal_approximation = decimal.Decimal.from_float

No need to define a new function, all you're doing is giving it a new 
name.  Actually, I think the existing name is clearer.

As for the name being too long, the real question is what's the purpose 
of the function.  It certainly doesn't give you an exact representation, 
as that cannot be done in general, without changing the defaults in the 
decimal module.  For example, try 2.0 ** -50    The exact decimal 
version of that needs 50 digits, and Python 3.1 docs say it uses 28 by 
default..

DaveA





More information about the Tutor mailing list