【问题标题】:Python: only print the result within a tolerance for a quadratic equationPython:仅在二次方程的公差范围内打印结果
【发布时间】:2020-07-17 08:25:01
【问题描述】:
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 中编写函数,从您的问题来看,只需 if 就足够了吧?
  • 'a 和 c 之间的差异在公差“tol”内是什么意思?
  • 您的问题不清楚。你所说的“tol”是什么意思,它是什么。 tol二次方程之间的关系是什么。

标签: python


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2020-06-20
    • 2022-01-12
    • 2017-08-10
    • 2016-02-04
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多