{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Floating point vs Program Logic" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What will the following code snippet do?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.1\n", "0.2\n", "0.30000000000000004\n", "0.4\n", "0.5\n", "0.6\n", "0.7\n", "0.7999999999999999\n", "0.8999999999999999\n", "0.9999999999999999\n", "1.0999999999999999\n", "1.2\n", "1.3\n", "1.4000000000000001\n", "1.5000000000000002\n", "1.6000000000000003\n", "1.7000000000000004\n", "1.8000000000000005\n", "1.9000000000000006\n", "2.0000000000000004\n", "2.1000000000000005\n", "2.2000000000000006\n", "2.3000000000000007\n", "2.400000000000001\n", "2.500000000000001\n", "2.600000000000001\n", "2.700000000000001\n", "2.800000000000001\n", "2.9000000000000012\n", "3.0000000000000013\n", "3.1000000000000014\n", "3.2000000000000015\n", "3.3000000000000016\n" ] }, { "ename": "KeyboardInterrupt", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrepr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0msleep\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0.1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mKeyboardInterrupt\u001b[0m: " ] } ], "source": [ "from time import sleep\n", "\n", "x = 0.0\n", "\n", "while x != 1.0:\n", " x += 0.1\n", " print(repr(x))\n", " \n", " sleep(0.1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How do you prevent that from happening?" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 0 }