Last active
December 31, 2015 03:39
-
-
Save mdboom/7929306 to your computer and use it in GitHub Desktop.
Timing of handling negative numbers raised to fractional powers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cmath | |
import timeit | |
def test_a(s, p): | |
try: | |
x = s ** p | |
except ValueError: | |
# on python2, sqrt(negative number) does not | |
# automatically lead to a complex number, but this is | |
# needed for the corner case of mag=-0.4*dex | |
x = cmath.exp(p * cmath.log(s)) | |
def test_b(s, p): | |
if s < 0.0 and p % 1.0 != 0.0: | |
x = cmath.exp(p * cmath.log(s)) | |
else: | |
x = s ** p | |
def test_a_neg(): | |
test_a(-0.4, 0.5) | |
def test_b_neg(): | |
test_b(-0.4, 0.5) | |
def test_a_pos(): | |
test_a(0.4, 0.5) | |
def test_b_pos(): | |
test_b(0.4, 0.5) | |
print min(timeit.repeat(test_a_neg, repeat=3, number=100000)) | |
print min(timeit.repeat(test_a_pos, repeat=3, number=100000)) | |
print min(timeit.repeat(test_b_neg, repeat=3, number=100000)) | |
print min(timeit.repeat(test_b_pos, repeat=3, number=100000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment