{"nbformat_minor": 0, "metadata": {"name": "", "signature": "sha256:b0caae8443128ddf93de5617c5ee49be9c5f7beb849b1f039a4b6affaaddf01c"}, "nbformat": 3, "worksheets": [{"metadata": {}, "cells": [{"source": ["# Picking apart a floating point number"], "metadata": {}, "cell_type": "markdown"}, {"metadata": {}, "prompt_number": 25, "language": "python", "input": ["\n", "# Never mind the details of this function...\n", "\n", "def pretty_print_fp(x):\n", " print(\"---------------------------------------------\")\n", " print(\"Floating point structure for %r\" % x)\n", " print(\"---------------------------------------------\")\n", " import struct\n", " s = struct.pack(\"d\", x)\n", "\n", " def get_bit(i):\n", " byte_nr, bit_nr = divmod(i, 8)\n", " return int(bool(\n", " s[byte_nr] & (1 << bit_nr)\n", " ))\n", "\n", " def get_bits(lsb, count):\n", " return sum(get_bit(i+lsb)*2**i for i in range(count))\n", "\n", " # https://en.wikipedia.org/wiki/Double_precision_floating-point_format\n", "\n", " print(\"Sign bit (1:negative):\", get_bit(63))\n", " exponent = get_bits(52, 11)\n", " print(\"Exponent: %d\" % (exponent - 1023))\n", " fraction = get_bits(0, 52)\n", " significand = fraction + 2**52\n", " print(\"Significand (binary):\", bin(significand)[2:])\n", " print(\"Shifted significand:\", repr(significand / (2**52)))"], "outputs": [], "cell_type": "code", "collapsed": false}, {"metadata": {}, "prompt_number": 24, "language": "python", "input": ["pretty_print_fp(1)"], "outputs": [{"output_type": "stream", "stream": "stdout", "text": ["---------------------------------------------\n", "Floating point structure for 1\n", "---------------------------------------------\n", "Sign bit (1:negative): 0\n", "Exponent: 0\n", "Significand (binary): 10000000000000000000000000000000000000000000000000000\n", "Shifted significand: 1.0\n"]}], "cell_type": "code", "collapsed": false}, {"source": ["Things to try:\n", "\n", "* Twiddle the sign bit\n", "* 1,2,4,8\n", "* 0.5,0.25\n", "* $2^{1023}$, $2^{1024}$\n", "* `float(\"nan\")`"], "metadata": {}, "cell_type": "markdown"}]}]}