HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Why is computing $e^x$ faster than computing $2^x$?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
fasterwhythancomputing

Problem

Here is a very closely related, but NOT a duplicate question.

One time, I decided to test how long it takes to compute $2^x$ compared to $e^x$ in Python. I expected $2^x$ to be faster as in binary, the base computers use, you can just append 0 to the number 1 $x$ times. I entered into Python IDLE (Python's Integrated Development and Learning Environment):
>>> import timeit
>>> timeit.timeit('2**100')
>>> 0.24405850004404783
>>> timeit.timeit('e**100','e=2.718281828459045')
>>> 0.10122330003650859


and found that $e^x$ was about twice as fast to compute, despite not being an integer. Why does this happen? (Note that this only happens for large numbers.) The only reason I can think of is that $e^x$ can be easily calculated using a MacLaurin series as $\frac d{dx} e^x$ is equal to $e^x$.

Solution

The reason is simple: 2100 returns a bignum, with full accuracy. There is more work to handle the bignum representation than mere binary shifts. On the opposite, e100 returns a float and uses the built-in power function of the processor.
>>> from timeit import timeit
>>> timeit('2**100')
0.20831729998462833
>>> timeit('2.0**100')
0.008533199987141415
>>> timeit('2.718281828459045**100')
0.008684300002641976
>>> timeit('e**100', 'e=2.718281828459045')
0.10991410000133328
>>> timeit('e**100', 'from math import e')
0.10929809999652207

Context

StackExchange Computer Science Q#160169, answer score: 5

Revisions (0)

No revisions yet.