floor() function and mathematical integers

Tim Peters tim.one at home.com
Sun May 27 20:37:43 EDT 2001


[Bengt Richter]
> ...
> UIAM, since digit has the last non-zero chunk, you could let the FPU
> count the trailing bits instead of using a while loop:
>
>     trailing_bits = math.frexp(float(digit^(digit-1)))[1]-1
>     top >>= trailing_bits
>     e += trailing_bits
> ...
> [and other efficiency tricks]

It would be a bad tradeoff for that particular routine:  it was written to
be "obviously correct", not maximally efficient.  It's fun that you *can*
pull low-level tricks like this in Python, though!  Best to reserve them for
when they're really needed.

> ...
> BTW, what's the preferred style for avoiding "magic numbers" in
> python code, with no #define SOME_CONSTANT?

By convention, write

SOME_CONSTANT = some_expression

at module level.  Modules are executed once per program run, the first time
they're imported, so you get the full power of the language in
"some_expression", and the efficiency of evaluating it only once.  It's
possible to write classes to enforce read-only-ness, but IMO they're far
more trouble than they're worth.  If you go changing the binding of an
ALL_UPPERCASE_NAME (it won't happen by accident!), you deserve whatever you
get.

> ...
> Another (python- ;-) newbie blurt: is it possible in python to define
> your own binary  (and unary too, for that matter) operator symbols?

No, you can only overload the existing ones, via defining special methods in
classes.

> Building on the % operator syntax, it might be nice to define
> named operators as name% so that you could, e.g., define
> a vector class using '*' for scalar multiply, but 'X%' or
> maybe VXP% for cross product, by defining __mul__ and __X__
> ( or __VXP__ ). It'd be nice to be able to control associativity
> and precedence too.
>
> Just defining the function __X__ in a particular scope would mean
> that a X% b would invoke __X__(a,b) or __X__(b) or __X__(a) depending
> on how it was defined.
>
> Would this ripple coolly or disastrously?

Depends entirely on who you ask <wink>; in general, it has a small but
sporadically intense constituency.  You may want to look at related Python
PEPs, here:

    http://python.sourceforge.net/peps/

especially

    PEP 211:  Adding New Linear Algebra Operators
    PEP 225:  Elementwise/Objectwise Operators

Guido's not a fan of extensible syntax, though.





More information about the Python-list mailing list