I've got a model like so:

class RunnerStat(models.Model):
    id_card= models.CharField(max_length=32)
    miles = models.PositiveSmallIntegerField()
    last_modified = models.DateField(auto_now=True)

I wish to create several RunnerStat instances with random miles values that average up to and including specific number.

I understand this may incorporate some statistics (distribution, etc.). Does anybody have pointers? Or done such like and may share some code?

Example: Create 100 RunnerStat objects with random miles values that average to 10.

Well for something to average to some specific number, they have to equal to a particular number. For example, if you would like 100 products to average to 10, the 100 products have to equal to 1000 since 1000/100 = 10.

One method to do that, which is not completely random is to develop a random number, then both take away and include that for your average, producing two RunnerStat products.

Which means you make a move such as this (note this really is from the mind and untested):

import random

avg = 10

n = random.randint(0,5)

r1 = RunnerStat(miles=avg-n)
r2 = RunnerStat(miles=avg+n)


Obviously complete another fields too. I simply place the miles within the RunnerStats. However that the RunnerStats should be a level number. You can write it to pass through inside a number and when it's odd the final you have to be exactly the quantity you want the typical to become.

When the average needs to be round the the given number although not exactly it you should use the random.gauss(mu, sigma) in the random module. This can produce a natural random group of of values which have an average (average) round the given value for mu having a standard deviation of sigma. The greater runners you produce the closer the mean will arrive at the preferred value.

import random

avg = 10
stddev = 5
n = random.gauss(avg,stddev)
for r in range(100):
  r = RunnerStat(miles=avg+n)

If you want the typical to become the precise number then you may always produce a runner (or even more reasonably a couple of runners) that counter balance no matter what your present difference in the mean is.