Last active
March 15, 2018 16:54
-
-
Save tigerhawkvok/5c619465f9ccab0eb25ee470708bbf16 to your computer and use it in GitHub Desktop.
Base Converter
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
#!python3 | |
def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): | |
""" | |
Convert a number to an arbitrary base | |
Parameters | |
---------------- | |
num: int, float | |
A numeric non-complex value | |
b: int | |
The base to cast the number into | |
numerals: str, list | |
a string or list representing the series of characters used in the set | |
""" | |
if b > len(numerals): | |
raise ValueError("Base is larger than the provided character pool") | |
if b < 2: | |
raise ValueError("Base must be >= 2") | |
strRep = str(num) | |
try: | |
import math | |
decimals = strRep[strRep.index(".") + 1:] | |
dOffsetLength = len(decimals) | |
dOffset = b ** dOffsetLength | |
num = math.floor(num * dOffset) | |
except ValueError: | |
# No decimal | |
dOffsetLength = 0 | |
converted = ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) | |
if dOffsetLength > 0: | |
negIndex = 0 - dOffsetLength | |
converted = str(converted)[:negIndex] + "." + str(converted)[negIndex:] | |
return converted | |
def weirdBase (b = 10.1, n = 9, loops = 1000): | |
""" | |
What's an infinite string number in a weird base? | |
e.g., .9999999... in base 10.1? | |
""" | |
nsum = 0 | |
for i in range(1, loops): | |
power = 0 - i | |
nsum += n * b ** power | |
return nsum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment