Within python3, if I have a dictionary containing for example:
d = {'C1': 0.68759, 'C2': -0.21432, 'H1': 0.49062, 'H2': -0.13267, 'H3': 0.08092, 'O1': -0.8604}
And I have the equation:
n1*d['C1'] + n2*d['H2'] + n3*d['C2'] + n4*d['H3'] + n5*d['O1'] + n6*d['H1'] = small_number
that I want to equal zero when rounding each d[key] value to 5 digits, for some scalars n1, n2, n3... that are positive integers. I also want to limit the amount that each dictionary value changes, say only change each value by a max of +- 0.0005. In this specific example:
n1, n2, n3, n4, n6 = 2, 2, 2, 4, 4, 2
Is there an easy, generalizable way to do this? By generalizable I mean the dictionary d could contain more key : value pairs, and the scalars n1, n2,... may be different (but always positive integers) as well. The length of dictionary d and number of scalars n will always be equal. It is fair to assume that in each case the value of small_number is on the order of 1E-5. If necessary I could possibly round to +- 1 more than 5 digits
I have thought about trying to subtract the nonzero portion of the equation from one specific key in the dictionary d, but I run into problems if for example the equation sums to 1E-5 and like in my example there are no scalars = 1. I could also use scipy.optimize.minimize and somehow define an objective function on a per-case basis as a function of the dictionary d and scalar values n, however I am not sure how to do this properly.
The scalar values n should not change
What is a "good solution"? This isn't as obvious as it seems. Goodness could be low error, or low coefficients, or a weighted mix of both. This demonstrates a solution where scipy tries to minimize error while treating coefficients as non-cost bounded decision variables.