Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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')
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__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment