Let's say I have a set of numbers.Now I want to find out by what additive combinations will they deviate from 0.2 the least(in total)? Each number can only pair with one other number.
For example, the numbers are 0.1, 0.15, 0.3, 0.2, and 0.13... Pair_1: 0.1 0.15, pair_2= 0.3 02... then let d_i be the deviation of pair i, how to find the additive combinations that achieve the minimal sum of d_i?
I have done a lot of thinking and searching, still could not solve this question by Python. One combination that deviate from 0.2 the least could cause another combination to deviate from it more.
SOS plz
CodePudding user response:
Here is some code I wrote to solve the problem based on my understanding of the question:
list_of_numbers = [0.1, 0.15, 0.3, 0.2, 0.13]
base_number = 0.2
def devianceFrom(number, list_of_numbers):
results = []
combinations = []
for i in range(0, len(list_of_numbers)):
for j in range(0, len(list_of_numbers)):
if j > i or j == i:
continue
else:
results.append(list_of_numbers[j] list_of_numbers[i])
combinations.append([list_of_numbers[j], list_of_numbers[i]])
for n in range(0, len(results)):
results[n] = abs(results[n]-number)
minCombo = min(results)
index = results.index(minCombo)
try:
for ind in index:
print("{} is the minimum difference using the sum of {} and {}.".format(results[ind], combinations[ind][0], combinations[ind][1]))
except:
print("{} is the minimum difference using the sum of {} and {}.".format(results[index], combinations[index][0], combinations[index][1]))
devianceFrom(base_number, list_of_numbers)
However, this will only find one set that is the minimum. So, if you need ALL combos that create the minimum difference then it will need sum modifications.
edit: The print that it gives is "0.03 is the minimum difference using the sum of 0.1 and 0.13."
If this is not the answer you are looking for please explain further. Also, I can send commented code or an explanation of the code if needed.