1π
If the average has to be around the the given number but not exactly it you can use the random.gauss(mu, sigma)
from the random module. This will create a more natural random set of of values that have a mean (average) around the given value for mu
with a standard deviation of sigma
. The more runners you create the closer the mean will get to the desired value.
import random
avg = 10
stddev = 5
n = random.gauss(avg,stddev)
for r in range(100):
r = RunnerStat(miles=avg+n)
r.save()
If you need the average to be the exact number then you could always create a runner (or more reasonably a few runners) that counter balance what ever your current difference from the mean is.
1π
Well for something to average to a specific number, they need to add up to a specific number. For instance, if you want 100 items to average to 10, the 100 items need to add up to 1000 since 1000/100 = 10.
One way to do this, which isnβt completely random is to generate a random number, then both subtract and add that to your average, generating two RunnerStat items.
So you do something like this (note this is from my head and untested):
import random
avg = 10
n = random.randint(0,5)
r1 = RunnerStat(miles=avg-n)
r2 = RunnerStat(miles=avg+n)
r1.save()
r2.save()
Of course fill in the other fields too. I just put the miles in the RunnerStats. The downside is that your RunnerStats must be an even number. You could write it to pass in a number and if it is odd the last one must be exactly the number you want the average to be.
- [Answered ]-Add popup in action of ModelAdmin
- [Answered ]-Load data into ModelForm fields in edit mode before it rendered
- [Answered ]-Getting multiple user objects using filter