Skip to content

Instantly share code, notes, and snippets.

@playpauseandstop
Created November 3, 2011 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save playpauseandstop/1336277 to your computer and use it in GitHub Desktop.
Save playpauseandstop/1336277 to your computer and use it in GitHub Desktop.
import unittest
from decimal import Decimal
from random import randint
class TestRandDecimal(unittest.TestCase):
def check(self, a, b):
value = randdecimal(a, b)
self.assertTrue(Decimal(a) <= value <= Decimal(b),
'not %r <= %r <= %r' % (a, value, b))
def test_result(self):
self.check(0, 10)
self.check('0.13', '0.20')
self.check(Decimal('5.33'), 10)
self.check(0, Decimal('5.33'))
self.check(Decimal('0.135'), Decimal('0.2'))
def test_same(self):
self.assertEqual(randdecimal(0, 0), 0)
self.assertEqual(randdecimal('0.2', '.2'), Decimal('.2'))
self.assertEqual(randdecimal(10, Decimal('10.00')), Decimal('10'))
def test_value_error(self):
self.assertRaises(ValueError, randdecimal, 10, 0)
self.assertRaises(ValueError, randdecimal, '0.2', '0.135')
self.assertRaises(ValueError,
randdecimal,
Decimal(10),
Decimal('5.33'))
def randdecimal(a, b):
"""
Return a random decimal N such that a <= N <= b.
"""
a, b = Decimal(a), Decimal(b)
diff = b - a
multiplier = pow(10, abs(diff.as_tuple()[2]))
diff_to_int = int(diff * multiplier)
return a + Decimal(randint(0, diff_to_int)) / multiplier
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment