2

I have a simulated annealing algorithm and I have a function like

result = w1*x1 + w2*x2 + ... + wn*xn

every loop of the simulated annealing when new w values are chosen how do you make sure that the sum of w always equal to 1 and that no individual w value is less that 0?

Thank you very much folks!

SARose
  • 3,558
  • 5
  • 39
  • 49
  • Have you tried directly translating that pseudocode into Python with `if sum(w) == 1 and all(item >= 0 for item in w)`? – TigerhawkT3 Dec 04 '15 at 03:37
  • You might not want to compare exactly to one, [lest you start thinking floating-point math is broken.](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Colonel Thirty Two Dec 04 '15 at 04:01
  • 1
    Are the w_i generated randomly? If true be aware that normalizing by their sum won't produce a uniform distribution. Look at [this answer](http://stackoverflow.com/a/29187687/4081336) to see how to solve this. – Leandro Caniglia Dec 04 '15 at 19:37
  • I think you're absolutely right @Leandro Caniglia – SARose Dec 04 '15 at 19:39

1 Answers1

6
  1. Use NumPy.
  2. That way, instead of result = w1*x1 + w2*x2 + ... + wn*xn you can do result = np.dot(w, x).
  3. The condition you want on w seems like it could come from:

    non_negative_w = np.abs(w)
    sum_w = np.sum(non_negative_w)
    normalized_non_negative_w = non_negative_w / sum_w
    
Curt F.
  • 4,690
  • 2
  • 22
  • 39