{ "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" ] }, { "ename": "KeyboardInterrupt", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mrepr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[0msleep\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0.1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;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": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.0+" } }, "nbformat": 4, "nbformat_minor": 0 }