Numpy array stuck in while loop if I enter a number greater than 0.1

Question:

What I am trying to do is :

Generating 6 random numbers which multipled for a coefficient and then added among themselves give me a value between overall – 0.5 and overall + 0.5. The program works fine with a coefficient in the last position of Gk_coeff (the sixth number of Gk_coeff[5]) which is <= 0.1, but if I enter 0.11, 0.12 (like in the code given) and so on, it stops working. There must be a reason but I really cannot think of it. I’ve tried using it on linux and windows and the issue persists, so it can’t be related to the system.

#!/usr/bin/env python3
import random
import numpy

overall = 83

Gk_coeff = [ 0.23, 0.23, 0.23, 0.23, 0.07, 0.12 ]
Gk_values = numpy.empty(6, dtype=int)

calculated_overall = 0

while not (overall - 0.5 <= calculated_overall <= overall + 0.5) :
    calculated_overall = 0
    for i in range (len(Gk_coeff)):
        Gk_values[i] = random.randint(overall - 7, overall + 7)
        calculated_overall += (Gk_values[i] * Gk_coeff[i])

print(calculated_overall)
Asked By: ciacciuli

||

Answers:

The while loop is not exited. The reason is that the random number calculated_overall you iteratively generate is, in expectation (and with a very high probability, larger than overall + 0.5. In particular, the reason is that

ExpectedValue[calculated_overall] = sum(Gk_coeff) * ExpectedValue[andom.randint(overall - 7, overall + 7)]
                                  = 1.11 * 83
                                  = 92.13

In turn, the condition for the while-loop always holds as calculated_overall practically never falls within the interval [82.5, 83.5].

Normalizing the weights so that they properly sum to 1.0 solves the issue, i.e.

Gk_coeff = [val/sum(Gk_coeff) for val in Gk_coeff]

provides a random number calculated_overall that has expected value of 83 and falls with a high probability within the interval [82.5, 83.5] those exiting the while loop.

Answered By: 7shoe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.