Python 解决二次方程程序

Python 解决二次方程程序

二次方程:

二次方程是由拉丁词“quadrates”组成,意思是平方。它是一种特殊类型的方程,具有以下形式:

2

在这里,“x”是未知数,你需要找到它,“a”,“b”,“c”表示指定的数字,其中“a”不等于0。如果a = 0,那么方程就变成线性的了,不再是二次方程。

在方程中,a、b和c被称为系数。

让我们举一个示例来解决二次方程8×2 + 16x + 8 = 0。

看看这个示例:

# import complex math module
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

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

# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2)) 

输出:

Enter a: 8
Enter b: 5
Enter c: 9
The solution are (-0.3125-1.0135796712641785j) and (-0.3125+1.0135796712641785j)

说明 –

第一行中,我们导入了 cmath 模块,并定义了三个变量a、b和c,它们从用户那里获取输入。然后,我们使用公式计算了判别式。使用 cmath.sqrt() 方法,我们计算了两个解并打印了结果。

第二种方法

我们可以使用直接公式获得二次方程的解。让我们理解以下示例。

上述公式包含以下情况。

  • 如果b 2 < 4ac,那么根是复数(非实数)。例如 – x 2 + x + 1,根是-0.5 + i1.73205和+0.5 – i1.73205。
  • 如果b 2 = 4ac,那么两个根相同。例如 – x 2 + x + 1,根是-0.5 + i1.73205和+0.5 – i1.73205。
  • 如果b 2 > 4ac,那么根是实数且不同。例如 – x 2 - 7 x – 12,根是3和4。

示例

# Python program to find roots of quadratic equation
import math


# function for finding roots
def findRoots(a, b, c):

    dis_form = b * b - 4 * a * c
    sqrt_val = math.sqrt(abs(dis_form))


    if dis_form > 0:
        print(" real and different roots ")
        print((-b + sqrt_val) / (2 * a))
        print((-b - sqrt_val) / (2 * a))

    elif dis_form == 0:
        print(" real and same roots")
        print(-b / (2 * a))


    else:
        print("Complex Roots")
        print(- b / (2 * a), " + i", sqrt_val)
        print(- b / (2 * a), " - i", sqrt_val)


a = int(input('Enter a:'))
b = int(input('Enter b:'))
c = int(input('Enter c:'))

# If a is 0, then incorrect equation
if a == 0:
    print("Input correct quadratic equation")

else:
    findRoots(a, b, c)

输出:

Enter a:7
Enter b:5
Enter c:2
Complex Roots
-0.35714285714285715  + i 5.5677643628300215
-0.35714285714285715  - i 5.5677643628300215

解释 –

在上述代码中,我们导入了math模块并定义了计算判别式的公式。然后我们定义了 findRoots 函数,它以三个整数值作为参数。然后我们使用if-elif-else语句检查了根。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程