0

I'm trying various ways to normalize array sum to 1, but it fails. E.g. the following code fails on Intel CPU and also Colab:

import numpy as np

a = 0.99
choice = 0
g = np.ones((9,)) * (1.0 - a)/8
g[choice] = a
print(np.sum(g), g)
g = g / np.sum(g) 
print(np.sum(g), g)
assert(np.sum(g) == 1.0)
Reza Roboubi
  • 198
  • 1
  • 9
  • 1
    Linked with floating point artihmetic, there are a numerous other posts about that on StackOverflow: https://stackoverflow.com/search?q=floating+point+arithmetic – Coding thermodynamist Mar 29 '23 at 13:27
  • 1
    Also: https://stackoverflow.com/tags/floating-point/info – Coding thermodynamist Mar 29 '23 at 14:01
  • @Nathan that's an excellent point! But then the answer on this page is wrong: https://stackoverflow.com/questions/46539431/np-random-choice-probabilities-do-not-sum-to-1 that's the problem that I'm trying to solve. What should I do?!! – Reza Roboubi Mar 29 '23 at 19:29
  • Ok, fair enough, maybe that answer isn't wrong! I'll try taking out my assertion or modifying it to see what happens. – Reza Roboubi Mar 29 '23 at 19:43

0 Answers0