Ask Your Question
-1

Dividing by 2 fast: how?

asked 11 years ago

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.

Preview: (hide)

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 ( 11 years ago )

1 Answer

Sort by » oldest newest most voted
1

answered 11 years ago

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

Preview: (hide)
link

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: 11 years ago

Seen: 364 times

Last updated: Dec 31 '13