# Programmer: Sriram Pemmaraju # Date: 3/5/2015 # This function "rounds" a given floating point number to the nearest "half integer" # provided the "half integer" is within distance 1/1000 and it returns that half integer. # Otherwise, the function returns None. By half integers, we mean elements in the set # {...-1.5, -1. -0.5, 0, 0.5, 1, 1.5,...} def nearHalfInteger(f): # We compute three candidates to compare f to # Note that we have to pay attention to whether # f is negative x = int(f) if x >= 0: y = x + 1/2 z = x + 1 else: y = x - 1/2 z = x - 1 # We check if there is candidate at distance <= 1/1000 # and if so, return it. if abs(f - x) <= 1/1000: return x elif abs(f - y) <= 1/1000: return y elif abs(f - z) <= 1/1000: return z return None