Ask Your Question
-1

Dividing by 2 fast: how?

asked 2013-12-23 03:43:39 +0200

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Please consider the following example:

tt=1200
ss=tt>>2
print ss
300

The division by 4 goes fast. But how can I divide by 2?

The expression tt>2 yields a boolean. And the options ss=tt//2 and ss=tt; ss/=2 seem not optimal.

timeit("tt=1200;ss=tt>>2")    625 loops, best of 3: 152 ns per loop
timeit("tt=1200;ss=tt//2")      625 loops, best of 3: 323 ns per loop
timeit("tt=1200;ss=tt;ss/=2") 625 loops, best of 3: 552 ns per loop

Thanks for you kind consideration.

edit retag flag offensive close merge delete

Comments

Is this homework? Do you understand what the bit-shift operator does? If not, look up http://docs.python.org/2/library/stdtypes.html#bitwise-operations-on-integer-types

ppurka gravatar imageppurka ( 2013-12-23 03:53:30 +0200 )edit

1 Answer

Sort by » oldest newest most voted
1

answered 2013-12-31 04:19:15 +0200

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

that should be tt>>1

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-12-23 03:43:39 +0200

Seen: 292 times

Last updated: Dec 31 '13