用Python程序求解一元二次方程


2022年5月1日, Learn eTutorial
1713

什么是一元二次方程?

在代数中,一元二次方程被定义为任何可以写成 ax² + bx + c = 0 形式的方程,其中 a、bc 是用户输入。x 是我们需要找出的未知数,且 a 不等于零。如果 a 等于零,那么它将是一个线性方程。

如何在Python中求解一元二次方程?

为了求解一元二次方程,我们使用公式 x = (-b + sqrt(b² - 4ac))/2a 或 x = (-b - sqrt(b² - 4ac))/2a,其中

  • b² - 4ac 被称为判别式。
  • 'a'、'b'、'c' 被称为系数

在这个Python程序中,我们必须导入复数数学模块 math.cmath,它是一个内置模块,用于处理复数的数学运算。cmath 也接受整数、浮点数和复数。cmath 模块的方法返回一个复数值。如果返回值是实数,它的虚部将为零。

在这个Python程序中,我们接收 a、b、c 的值,并使用浮点数据类型将其转换为浮点数。现在我们必须使用公式 (b**2) - (4*a*c) 找出判别式 d,并应用该判别式来计算 sol1sol2。最后,打印结果。

算法

第一步: 导入 cmath 模块以进行复数计算。

第二步: 使用Python语言中的 input 函数接收系数 a、bc 的值,并使用浮点数据类型将该字符串转换为浮点数。

第三步: 现在,我们必须使用方程 b**2 - 4*a*c 计算判别式 'd',并且我们必须将该判别式应用于主一元二次方程中。

第四步: 现在,我们找到一元二次方程的解 (-b-cmath.sqrt(d))/(2*a) 并将结果保存在变量 'sol1' 和 sol2 中。

第五步: 使用 format 方法打印结果。


注意:format 方法用于格式化结果并将该值插入到格式占位符中。在这里,我们在 format 方法中使用{}括号作为占位符。format 方法返回字符串值。

Python 源代码

                                          import cmath  
a = float(input('Enter the value a: '))  
b = float(input('Enter the value b: '))  
c = float(input('Enter the value c: '))  
  

d = (b**2) - (4*a*c)     # calculating the discriminant
  

sol1 = (-b-cmath.sqrt(d))/(2*a)    # Applying the discriminant in the quadratic formula
sol2 = (-b+cmath.sqrt(d))/(2*a)  
print('The result is {0} and {1}'.format(sol1,sol2))    # print the result using the format method
                                      

输出

Enter the value a: 8
Enter the value a: 16
Enter the value a: 8

The result is  -1 + 0j and -1 + 0j