源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python编程实现数学运算求一元二次方程的实根算法示例

  • 时间:2022-10-22 02:30 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python编程实现数学运算求一元二次方程的实根算法示例
本文实例讲述了Python编程实现数学运算求一元二次方程的实根算法。分享给大家供大家参考,具体如下: [b]问题:[/b] 请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:ax² + bx + c = 0的两个解。 [b]实现代码:[/b]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def quadratic(a,b,c):
  if a == 0:
    raise TypeError('a不能为0')
  if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)):
    raise TypeError('Bad operand type')
  delta = math.pow(b,2) - 4*a*c
  if delta < 0:
    return '无实根'
  x1= (math.sqrt(delta)-b)/(2*a)
  x2=-(math.sqrt(delta)+b)/(2*a)
  return x1,x2
print(quadratic(2,3,1))
print(quadratic(1,3,-4))

运行效果图如下: [img]http://files.jb51.net/file_images/article/201704/201742121928219.jpg?201732154348[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部