Advertisement
Guest User

cmpfloat.py

a guest
Dec 9th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. #!/usr/bin/python3
  2. #-*-python-*-
  3. '''Compare two files while tolerating small errors in floating point numbers.
  4. Written by Hao Chen, 2015'''
  5. import sys, shlex, argparse
  6.  
  7. def makeshlex(filename):
  8.     myshlex = shlex.shlex(open(filename), filename, True)
  9.     # For decimal and scientific notation float
  10.     myshlex.wordchars='0123456789.-+eE'
  11.     myshlex.whitespace=''
  12.     return myshlex
  13.  
  14. def notequal(f1, f2):
  15.     return (abs(f1 - f2) * 0x400) > max(abs(f1), abs(f2), 1)
  16.  
  17. def differ(file1, file2):
  18.     if not options.silent:
  19.         print('{} {} differ'.format(file1, file2), file=sys.stderr)
  20.  
  21. parser = argparse.ArgumentParser(
  22.     description='Compare two files ignoring small differences in float point values.')
  23. parser.add_argument('-s', '--silent', action = 'store_true',
  24.                     default = False,
  25.                     help = 'Output nothing; yield exit status only.')
  26. parser.add_argument('-d', '--debug', action = 'store_true',
  27.                     default = False,
  28.                     help = 'Debug mode. Output tokens.')
  29. parser.add_argument('file1', type=str)
  30. parser.add_argument('file2', type=str)
  31. options = parser.parse_args()
  32.  
  33. filename1 = options.file1
  34. filename2 = options.file2
  35. file1 = makeshlex(filename1)
  36. file2 = makeshlex(filename2)
  37.  
  38. t1 = file1.get_token()
  39. t2 = file2.get_token()
  40. while t1 is not None and t2 is not None:
  41.     f1 = None
  42.     f2 = None
  43.     try:
  44.         f1 = float(t1)
  45.         f2 = float(t2)
  46.     except ValueError:
  47.         pass
  48.     if f1 is None or f2 is None:
  49.         # f1 and/or f2 are not float
  50.         if t1 != t2:
  51.             differ(filename1, filename2)
  52.             exit(1)
  53.     else:
  54.         # both f1 and f2 are float
  55.         if options.debug:
  56.             print('{}:{}:'.format(t1,t2), file=sys.stderr)
  57.         if notequal(f1, f2):
  58.             differ(filename1, filename2)
  59.             exit(1)
  60.     t1 = file1.get_token()
  61.     t2 = file2.get_token()
  62.  
  63. if t1 is None and t2 is None:
  64.     exit(0)
  65. else:
  66.     differ(filename1, filename2)
  67.     exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement