Floating Point Numbers
Real numbers are represented on computers by floating point numbers. These contain finite numbers of sign, exponent and fraction bits:
Here is Python code that interprets IEEE 64 bit standard floating point numbers:
Here is Python code that interprets IEEE 64 bit standard floating point numbers:
#!/usr/bin/env python3 FP_LEN = 64 SIGN_LEN = 1 EXP_LEN = 11 EXP_HALF = 2 ** EXP_LEN / 2 FRAC_LEN = FP_LEN - SIGN_LEN - EXP_LEN BINARY = 2 def floating_point(bit_string): """ Interprets IEEE 64 bit standard floating point numbers. """ sign = int(bit_string[0], BINARY) exponent = int(bit_string[1:1 + EXP_LEN], BINARY) - EXP_HALF + 1 fraction = int("1" + bit_string[-FRAC_LEN:], BINARY) / 2 ** FRAC_LEN if exponent == -EXP_HALF + 1: print("SPECIAL CASE: subnormal") exponent += 1 fraction -= (1 << FRAC_LEN) / 2 ** FRAC_LEN elif exponent == EXP_HALF: if fraction == (1 << FRAC_LEN) / 2 ** FRAC_LEN: if sign: print("SPECIAL CASE: -infinity") else: print("SPECIAL CASE: infinity") else: print("SPECIAL CASE: undefined") exponent = fraction = 0 return (-1) ** sign * (2 ** exponent) * fraction
Comments
Post a Comment