首页 > 解决方案 > Python:仅在二次方程的公差范围内打印结果

问题描述

print("input a, b and c for a quadratic equation ax^2+bx+c=0")
a = float(input("a ="))
b = float(input("b ="))
c = float(input("c ="))


D = (b**2) - (4*a*c)

if D>0: 
 s1 = (-b+D**0.5)/(2*a)
 s2 = (-b-D**0.5)/(2*a)
 print("the two solutions are: {} and {}".format(s1,s2))

elif D==0:
 s3 = (-b)/(2*a)
 print("the one solution is: {}".format(s3)) 

elif D<0:
 print("no solution")

此代码有效,但我需要将此代码制作成一个函数,如果 a 和 c 之间的差异在公差“tol”之内,则仅打印 c,不知道如何继续。

标签: python

解决方案


您可以使用 Python 的内置abs函数或 NumPy 的isclose函数。

您可以添加另一个if条件为abs(a - c) < tolor的语句np.isclose(a, c),同时将atol(绝对容差)或rtol(相对容差)可选参数指定为所需值。

参考:https ://numpy.org/doc/stable/reference/generated/numpy.isclose.html


推荐阅读