Last active
October 21, 2020 10:56
-
-
Save Plutor/5339262 to your computer and use it in GitHub Desktop.
Decimal to pinary conversion
This file contains 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
"""Convert decimal numbers to pinary (base pi). | |
Fractional and even irrational bases are possible, but aren't really useful for | |
anything. Base pi has four digits: 0, 1, 2, and 3. What's interesting is that | |
there's some "space" between the highest digit and the base, which means that | |
there are numbers with multiple valid representations. You'll notice: | |
decimal 7.000000 = pinary 20.2021120021 | |
decimal 8.000000 = pinary 21.2021120021 | |
decimal 9.000000 = pinary 22.2021120021 | |
decimal 10.000000 = pinary 100.0102212222 | |
Wait, what about pinary 23.202..? That's also equal to 10. What about 30(pi), | |
31(pi), etc? Well, 31(pi) is 10.424, which is greater than 100(pi). Both 32(pi) | |
and 33(pi) are also greater than 100(pi). | |
A fun thought experiment, but not very useful otherwise. | |
""" | |
import math | |
import sys | |
val = float(sys.argv[1]) | |
try: | |
digits = int(sys.argv[2]) | |
except: | |
digits = 5 | |
sys.stdout.write('decimal %f = pinary ' % val) | |
# The highest max digit needed is log_pi(val) | |
for place in range(int(math.log(val, math.pi)), -digits-1, -1): | |
place_val = math.pow(math.pi, place) | |
digit = math.floor(val / place_val) | |
assert digit <= 3 | |
val -= (place_val * digit) | |
sys.stdout.write('%d' % digit) | |
if place == 0: | |
sys.stdout.write('.') | |
print '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just what I was looking for. Awesome.