Advertisement
Guest User

Untitled

a guest
Nov 24th, 2011
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. from random import random
  2. from math import log10,log
  3.  
  4. def roundf(f):
  5.     epsilon = 2.0**(log(f,2) - 51.0)
  6.     return round(f + cmp(f,0)*epsilon,2)
  7.  
  8. def test_rounding():
  9.     " Test the rounding function for up to 14 digits precision "
  10.     fractions = [.015, .01499, .675, .67499]
  11.     expecteds = ['.02', '.01', '.68', '.67']
  12.     magnitudes = range(10)
  13.     c = 0
  14.     for mag in magnitudes:
  15.         for i in xrange(len(fractions)):
  16.             for x in xrange(10000):
  17.                 frac = fractions[i]
  18.                 exp = expecteds[i]
  19.                 n = int(random()*pow(10,mag)) + frac
  20.                 rounded = str(roundf(n))
  21.                 assert rounded.endswith(exp)
  22.                
  23. test_rounding()
  24.  
  25.  
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement