开发者

Django: Creating model instances with a random integer field value that average up to a specified number

I have 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 want to create several RunnerStat instances with random miles values that average up to a specific number.

I know this might involve s开发者_开发百科ome statistics (distribution, etc.). Does anyone have any pointers? Or done something similar and could share some code?

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜