Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- #-*-python-*-
- '''Compare two files while tolerating small errors in floating point numbers.
- Written by Hao Chen, 2015'''
- import sys, shlex, argparse
- def makeshlex(filename):
- myshlex = shlex.shlex(open(filename), filename, True)
- # For decimal and scientific notation float
- myshlex.wordchars='0123456789.-+eE'
- myshlex.whitespace=''
- return myshlex
- def notequal(f1, f2):
- return (abs(f1 - f2) * 0x400) > max(abs(f1), abs(f2), 1)
- def differ(file1, file2):
- if not options.silent:
- print('{} {} differ'.format(file1, file2), file=sys.stderr)
- parser = argparse.ArgumentParser(
- description='Compare two files ignoring small differences in float point values.')
- parser.add_argument('-s', '--silent', action = 'store_true',
- default = False,
- help = 'Output nothing; yield exit status only.')
- parser.add_argument('-d', '--debug', action = 'store_true',
- default = False,
- help = 'Debug mode. Output tokens.')
- parser.add_argument('file1', type=str)
- parser.add_argument('file2', type=str)
- options = parser.parse_args()
- filename1 = options.file1
- filename2 = options.file2
- file1 = makeshlex(filename1)
- file2 = makeshlex(filename2)
- t1 = file1.get_token()
- t2 = file2.get_token()
- while t1 is not None and t2 is not None:
- f1 = None
- f2 = None
- try:
- f1 = float(t1)
- f2 = float(t2)
- except ValueError:
- pass
- if f1 is None or f2 is None:
- # f1 and/or f2 are not float
- if t1 != t2:
- differ(filename1, filename2)
- exit(1)
- else:
- # both f1 and f2 are float
- if options.debug:
- print('{}:{}:'.format(t1,t2), file=sys.stderr)
- if notequal(f1, f2):
- differ(filename1, filename2)
- exit(1)
- t1 = file1.get_token()
- t2 = file2.get_token()
- if t1 is None and t2 is None:
- exit(0)
- else:
- differ(filename1, filename2)
- exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement