{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "import math" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "class Quadratic :\n", " \"\"\"Codes a class for quadratic polynomials.\n", " Attributes (class variables) :\n", " a, b, c : coefficients of ax^2 + bx + c.\n", " Methods (class functions) :\n", " roots() : returns a tuple containing the roots\n", " __call__(x) : returns the value of the poly at x.\n", " display() : displays the equation.\n", " \"\"\"\n", " \n", " def __init__(self, a, b, c) :\n", " self.a = a\n", " self.b = b\n", " self.c = c\n", " \n", " def __call__(self, x) :\n", " return self.a *x*x + self.b *x + self.c\n", " \n", " def roots(self) :\n", " a = self.a\n", " b = self.b\n", " c = self.c\n", " \n", " if a == 0 :\n", " if b == 0 :\n", " print \"Constant = 0\"\n", " rval = None\n", " else :\n", " rval = - float(c)/b\n", " else :\n", " if b*b - 4*a*c < 0 :\n", " print \"Complex roots.\"\n", " rval = None\n", " else :\n", " x1 = (-b + math.sqrt(b*b - 4*a*c))/(2*a)\n", " x2 = (-b - math.sqrt(b*b - 4*a*c))/(2*a)\n", " rval = (x1, x2)\n", " return rval\n", " \n", " def __str__(self) :\n", " return \"%g x^2 + %g x + %g\" %(self.a, self.b, self.c)\n", " def __repr__(self) :\n", " return self.__str__()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "q = Quadratic(4, 4, 1)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "if __name__ == '__main__' :\n", " print q.roots()\n", " print q(1)\n", " print q" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(-0.5, -0.5)\n", "9\n", "4 x^2 + 4 x + 1\n" ] } ], "prompt_number": 4 } ], "metadata": {} } ] }