Created
          January 26, 2014 16:52 
        
      - 
      
 - 
        
Save bendmorris/8635657 to your computer and use it in GitHub Desktop.  
    Testing whether Python's json module correctly outputs floating point numbers without loss of precision
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import random | |
| import json | |
| digits = '0123456789' | |
| for i in range(10000): | |
| ndigits = 10 | |
| number = '0.' + ''.join([random.choice(digits) for j in range(ndigits)]) | |
| number = number.rstrip('0') | |
| if number.endswith('.'): number += '0' | |
| json_number = json.dumps(float(number)) | |
| try: | |
| assert (json_number == number) | |
| except AssertionError: | |
| if not ('e' in json_number and float(json_number) == float(number)): | |
| print 'Not the same:', number, float(number), json.dumps(float(number)) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment