4 ms·
Why does the Bernoulli formula take exponentially long in the exponent? Python’s native form (using either an integer or float exponent) and even an arbitrary p
by dbaupp 7y ago
Why does the Bernoulli formula take exponentially long in the exponent? Python’s native form (using either an integer or float exponent) and even an arbitrary percision computation to 1000 decimal digits using mpmath (also with either an integer or float exponent) are fast even for much larger exponents, and are accurate.
>>> import math, timeit
>>> x = 2**52
>>> math.e
2.718281828459045
>>> (1+1/x)**x
2.718281828459045
>>> timeit.timeit(lambda: (1+1/x)**x, number = 10**6) / 10**6
2.1324560802895575e-07
>>> timeit.timeit(lambda: (1+1/x)**float(x), number = 10**6) / 10**6
3.0082468304317444e-07
>>> from mpmath import mp
>>> mp.dps = 1000
>>> (1+1/mp.mpf(x))**x
mpf(‘2.7182818284590449335703801338125114…’)
>>> timeit.timeit(lambda: (1+1/mp.mpf(x))**x, number = 10**3) / 10**3
0.0004724335519131273
>>> timeit.timeit(lambda: (1+1/mp.mpf(x))**mp.mpf(x), number = 10**3) / 10**3
0.00047394841397181155
(Times in seconds.)