9. Python | 自定义函数_求一元二次方程根(代码)
2019-03-31 本文已影响38人
家和万事亨
练习
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:ax2 + bx + c = 0的两个解。
提示:计算平方根可以调用math.sqrt()函数:
# -*- coding:utf-8 -*-
import math
def quadratic(a,b,c):
if not isinstance(a+b+c,(int,float)):
raise TypeError('bad operand type')
elif a != 0:
# ∆ = b²-4ac > 0时,有两个解
if b*b - 4*a*c > 0:
x1 = (-b + math.sqrt(b*b - 4*a*c))/2/a
x2 = (-b - math.sqrt(b*b - 4*a*c))/2/a
return ('x1 =',x1,'x2 =',x2)
# Δ = b²-4ac = 0时,有一个解
elif b*b - 4*a*c == 0:
return ('x =',-b/2/a)
# Δ = b²-4ac < 0时,无解
else:
return ('x无解')
else: # a = 0时,变为一元一次方程
if b != 0:
return ('x =',-c/b)
else:
if c == 0: # b = 0,c = 0时,x可以取任意值
return ('x为任意值')
else: # b = 0,c != 0时,方程无解
return ('x无解')
# 测试:
'''
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))
if quadratic(2, 3, 1) != (-0.5, -1.0):
print('测试失败')
elif quadratic(1, 3, -4) != (1.0, -4.0):
print('测试失败')
else:
print('测试成功')'''
print('quadratic(0,3,3)=',quadratic(0,3,3))