gpt4 book ai didi

python - 二次方程式混合

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:04 24 4
gpt4 key购买 nike

所以我编写了一个 python 代码,使用二次公式求解 x。除了迹象,一切最终都会成功。例如,如果你想因式分解 x^2 + 10x + 25,当答案应该是 5、5 时,我的代码输出 -5、-5。

def quadratic_formula():
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
bsq = b * b
fourac = 4 * a * c
sqrt = (bsq - fourac) ** (.5)
oppb = -b
numerator_add = (oppb) + (sqrt)
numerator_sub = (oppb) - (sqrt)
twoa = 2 * a
addition_answer = (numerator_add) / (twoa)
subtraction_answer = (numerator_sub) / (twoa)
print(addition_answer)
print(subtraction_answer)

最佳答案

您的解决方案很好,让我们使用 sympy 来证明它:

>>> (x**2+10*x+25).subs(x,-5)
0

如您所见,-5 是根之一,而 5

>>> (x**2+10*x+25).subs(x,5)
100

不是,现在......如果你扩展你的 2 个根 [-5,-5] 就像:

>>> ((x+5)*(x+5)).expand()
x**2 + 10*x + 25

你可以看到结果匹配。

其实你也可以通过显示二次方程来确认根是正确的:

enter image description here

我强烈建议您查看 The Quadratic Formula 的概念等一切都清楚了就回到编码上

关于python - 二次方程式混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com