Created
September 28, 2018 14:22
-
-
Save shimpe/50e031e3449411e8cca347efb6c38826 to your computer and use it in GitHub Desktop.
approach numbers using limited number of positive exponents
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
import math | |
import itertools | |
from operator import mul | |
from functools import reduce | |
def approx(freq, exponents): | |
resulting_list = [] | |
maxvals = [ list(range(0, math.ceil(math.log(freq, exp)))) for exp in exponents] | |
print("maxvals = ", maxvals) | |
cartesian_product = itertools.product(*maxvals) | |
cartesian_prod_list = [] | |
for idx, element in enumerate(cartesian_product): | |
#print ("element = ", element) | |
produced_freq = reduce(mul, [math.pow(exponents[i], element[i]) for i in range(len(exponents))]) | |
#print ("produced freq = ", produced_freq, element) | |
diff = math.fabs(freq-produced_freq) | |
#print ("diff between desired and produced: ", diff) | |
energy = reduce(mul, [e+1 for e in element]) | |
#print ("product of (exponents+1): ", energy) | |
resulting_list.append([diff, energy, idx]) | |
cartesian_prod_list.append(element) | |
result = sorted(resulting_list, key=lambda el : (el[0], el[1])) | |
# print best result | |
#print(result[0]) | |
print(cartesian_prod_list[result[0][2]]) | |
total = 1 | |
for idx, exponent in enumerate(cartesian_prod_list[result[0][2]]): | |
total = total * (math.pow(exponents[idx], exponent)) | |
print ("desired: ", freq, " reached: ", total, "diff: ", math.fabs(total-freq), "diff[%]: ", math.fabs(total-freq)/freq*100) | |
if __name__=="__main__": | |
approx(440, [2,3,5,7,11,13,17,19,23]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment