首页 > 解决方案 > 如何在我的 python 代码中编写 x^2?有人可以给我关于我的代码的建议吗

问题描述

二次方程计算器和我使用的代码效果不佳。代码有一些错误。

我已经尝试过使用基本数字,例如 1/2/3。没有等式。代码仍然不起作用。实际工作的事情是只放置变量,仅此而已。在我按回车键查看答案后,它说我的代码有一些错误。

print ("Quadratic Equation Calculator")

import math

print ("Enter the first variable : ")
first = float(input(''))
print ("Enter the second variable : ")
second = float(input(''))
print ("Enter the third variable : ")
third = float(input(''))

Answer1 = ((-1 * second) - math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)
Answer2 = ((-1 * second) + math.sqrt((math.pow(second, 2) - 4.0*first*third))) / (2*first)

print (Answer1)
print (Answer2)

我希望能正确回答问题,这个方程计算器可用于实际方程和使用变量。x平方和3x之类的。

标签: pythonsymbolic-math

解决方案


在 python x ^ 2 中,可以是 x ** 2、x * x 或 pow(x, 2)。其他人给了你很好的建议,我想补充一些。二次方程:ax^2 + bx + c = 0(调整使方程等于零!)具有多项式项 ax^2、bx、c;其系数为 a, b。而 c 是常数项。然后是二次公式: (-b + sqrt(b ^ 2 - 4 * a * c)) / 2a; 求解 x。

以上所有内容都正确地出现在您的代码中但是,如果解决方案停留在复数集合 {C} 中,您将遇到麻烦。

这可以通过衡量“判别式”轻松解决。

判别式是 b^2 - 4ac,并且

  • 如果判别式 = 0,则只有一种解
  • 如果判别式 > 0,则有两个实解
  • 如果判别式 < 0,则有两个复解

考虑到上述情况,代码应如下所示:

import math


print ("Quadratic Equation Calculator")

a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))

discriminant = pow(b, 2) - 4.0 * a * c

if discriminant == 0:
    root1 = root2 = (-1 * b) / (2 * a)
elif discriminant < 0:
    root1 = ((-1 * b) - math.sqrt(-discriminant) * 1j) / (2 * a)
    root2 = ((-1 * b) + math.sqrt(-discriminant) * 1j) / (2 * a)
else:
    root1 = ((-1 * b) - math.sqrt(discriminant)) / (2 * a)
    root2 = ((-1 * b) + math.sqrt(discriminant)) / (2 * a)

print (root1)
print (root2)

类似的 SO 答案:https ://stackoverflow.com/a/49837323/8247412

下面我更改了代码以支持 python 编程,因为 numpy 可以找到具有威力的多项式(二次和更高阶)方程的根。 numpy.roots

import numpy as np
print ("Quadratic Equation Calculator")

a = float(input("Enter the coefficient of term `x ^ 2` (degree 2), [a]: "))
b = float(input("Enter the coefficient of term `x` (degree 1), [b]: "))
c = float(input("Enter the constant term (degree 0), [c]: "))

coeffs = [a, b, c]  # or d, e and so on..
roots = np.roots(coeffs)
print (roots)

推荐阅读