68 lines
1.6 KiB
Python
68 lines
1.6 KiB
Python
"""Karma logging models."""
|
|
|
|
import logging
|
|
import math
|
|
import pytz
|
|
import random
|
|
|
|
from django.conf import settings
|
|
from django.db import models
|
|
|
|
|
|
log = logging.getLogger('pi.models')
|
|
|
|
|
|
class PiLogManager(models.Manager):
|
|
|
|
"""Assemble some queries against PiLog."""
|
|
|
|
def simulate(self):
|
|
"""Add one more entry to the log, and return it."""
|
|
|
|
try:
|
|
latest = self.latest()
|
|
except PiLog.DoesNotExist:
|
|
latest = PiLog(count_inside=0, count_total=0)
|
|
latest.save()
|
|
|
|
inside = latest.count_inside
|
|
total = latest.count_total
|
|
|
|
x = random.random()
|
|
y = random.random()
|
|
hit = True if math.hypot(x,y) < 1 else False
|
|
|
|
if hit:
|
|
newest = PiLog(count_inside=inside+1, count_total=total+1)
|
|
else:
|
|
newest = PiLog(count_inside=inside, count_total=total+1)
|
|
newest.save()
|
|
|
|
return newest, x, y, hit
|
|
|
|
|
|
class PiLog(models.Model):
|
|
|
|
"""Track pi as it is estimated over time."""
|
|
|
|
count_inside = models.PositiveIntegerField()
|
|
count_total = models.PositiveIntegerField()
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
|
|
objects = PiLogManager()
|
|
|
|
class Meta:
|
|
get_latest_by = 'created'
|
|
|
|
def __str__(self):
|
|
"""String representation."""
|
|
|
|
tz = pytz.timezone(settings.TIME_ZONE)
|
|
return "({0:d}/{1:d}) @ {2:s}".format(self.count_inside, self.count_total,
|
|
self.created.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S %Z'))
|
|
|
|
def value(self):
|
|
"""Return this log entry's value of pi."""
|
|
|
|
return 4.0 * int(self.count_inside) / int(self.count_total)
|