{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "from __future__ import division\n", "\n", "# ^^ what's this about?" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "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", " print \"Hex pattern:\", \" \".join(\"%02x\" % ord(i) for i in s[::-1])\n", "\n", " def get_bit(i):\n", " byte_nr, bit_nr = divmod(i, 8)\n", " return int(bool(\n", " ord(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 xrange(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 (unshifted: %d = 0x%x)\" % (exponent - 1023, exponent, exponent)\n", " fraction = get_bits(0, 52)\n", " print \"Fraction:\", hex(fraction)\n", " significand = fraction + 2**52\n", " print \"Significand:\", hex(significand)\n", " print \"Shifted significand:\", repr(significand / (2**52))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "pretty_print_fp(1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "---------------------------------------------\n", "Floating point structure for 1\n", "---------------------------------------------\n", "Hex pattern: 3f f0 00 00 00 00 00 00\n", "Sign bit (1:negative): 0\n", "Exponent: 0 (unshifted: 1023 = 0x3ff)\n", "Fraction: 0x0\n", "Significand: 0x10000000000000\n", "Shifted significand: 1.0\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Examples to try:\n", "\n", "- 1\n", "- 1+2**-52\n", "- 0\n", "- 1+2**-53\n", "- 1-2**-52\n", "- 1-2**-53\n", "- NaN\n", "- What value should we try to see a denormal?\n" ] } ], "metadata": {} } ] }