python - 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 的内置abs
函数或 NumPy 的isclose
函数。
您可以添加另一个if
条件为abs(a - c) < tol
or的语句np.isclose(a, c)
,同时将atol
(绝对容差)或rtol
(相对容差)可选参数指定为所需值。
参考:https ://numpy.org/doc/stable/reference/generated/numpy.isclose.html
推荐阅读
- php - 如何获取当前 wordpress 帖子的页数?
- node.js - 用于电子商务的 MongoDB 数据库模式
- ios - iOS 上的推送通知渐进式 Web 应用
- android - akpanalyzer 和 dex2jar 有什么区别?
- java - 从弹出窗口中选择一个复选框,然后使用 selenium webdriver 使用按钮将其关闭
- javascript - 如何从触摸事件中获取 DOM 元素?
- android - 如何将数据从 Intent Service 发送回 Activity 并继续执行?
- tcl - 使用 TCL 向 Telnet 发送参数
- tensorflow - tf.Session() 上的分段错误(核心转储)
- javascript - Javascript:为什么 onclick 事件仅适用于构建链接的 for 循环的最后一次迭代?