Home > Net >  How can generate n numbers in the interval [a,b] that their summation doesn't exceed k in pytho
How can generate n numbers in the interval [a,b] that their summation doesn't exceed k in pytho

Time:07-27

Let me I from the question in an easy way:

I usually have about k=3000€ per month. This month had n=26 working days, and generally, I work something between [100,120]€ each day.

Note: k could be /- x€ if needed, but it should be as minimum as possible.

what I tried to generate n numbers within [a,b] interval, but it should be very close to the k:

import numpy as np
#rng = np.random.default_rng(123)
#arr1 = rng.uniform(100, 120,26)
arr1 = np.random.randint(100,120,26)

#array([107, 115, 116, 105, 104, 110, 110, 107, 116, 110, 101, 112, 109,
#       111, 118, 102, 108, 113, 101, 112, 111, 116, 111, 109, 110, 107])

total = np.sum(arr1)
print(f'Sum of all the elements is {total}')
#Sum of all the elements is 2851

I don't have any clue to fulfil the condition. The summation of generated random numbers should be close to k [k, k i] i=minimum e.g. [3000€, 3050€].

CodePudding user response:

You can use a Gaussian distribution for a given mean and standard deviation

mu = 3000/26

sigma = 5 ## allowed deviation from mean  - 5 from mean i.e [110.4,120.4]

arr1 = np.random.normal(mu, sigma, 26)

print(np.sum(arr1))
# 3011.268333226019

You can also play with other distributions and see which fits your purpose.

CodePudding user response:

Disclaimer:

As far as I know, there isn't any built in way to do this. Below is a possible solution.

Possible Solution:

You could run it, then find the difference between 3,000 and the number that the program printed. You could split that by the number of days there are and add that number to all the days.

Example:

The sum is 2896, so subtract that from 3,000. This is 104, and divide that by the number of days (26) to get 4. Add 4 to all the numbers.

Important Notes:

You would have to double check that the numbers aren't above the maximum allowed. Also, if the number printed happened to be more than 3,000, you would have to do this except with subtraction. If you're doing this, you have to double check that the numbers aren't above the minimum allowed.

  • Related