"""Find the nearest power of 2 below and above an input number, along
with the diffs.
"""
import argparse
import math
import sys
def nearest_powers_of_two(num, output=True):
"""Find the powers of 2 nearest the input num, along with the diffs.
If optional parameter output == True (the default), print the
values as well as returning them. Return value is a list of tuples
[(low, lowdiff), (high, highdiff)].
"""
lg = math.floor(math.log2(num))
lo = math.floor(math.pow(2, lg))
hi = math.floor(math.pow(2, lg+1))
lodiff = abs(lo-num)
hidiff = abs(hi-num)
lopower = round(math.log2(lo))
hipower = round(math.log2(hi))
if output:
print(f'low power of two: {lo} (2**{lopower}), diff={lodiff}')
print(f'high power of two: {hi} (2** {hipower}), diff={hidiff}')
return [(lo, lodiff), (hi, hidiff)]
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
'number',
type=int,
help='Number for which to find neighboring powers of 2.')
args = parser.parse_args()
nearest_powers_of_two(args.number)
if __name__ == "__main__":
main(sys.argv)
quit()