{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 一元二次方程\n", "求根:用math.sqrt(x)可以求x的根\n", "$$\n", "x = \\dfrac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}\n", "$$\n", "代码如下:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "import math\n", "def qiugen(a,b,c):\n", " dc = b/-2*a #对称轴\n", " print (\"对称轴\"+str(dc))\n", "\n", " try: #尝试求根,因为负数没法求根\n", " x1 = -b+math.sqrt(b**2-4*a*c)/2*a\n", " x2 = -b-math.sqrt(b**2-4*a*c)/2*a\n", " if x1 == x2:\n", " return \"只有一个解\",x1\n", " else:\n", " return \"两个解\",x1,x2\n", " \n", " except: \n", " return \"没有根\"\n", " " ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "对称轴-1.0\n" ] }, { "data": { "text/plain": [ "('只有一个解', -2.0)" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "qiugen(1,2,1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.6.13" } }, "nbformat": 4, "nbformat_minor": 4 }