Solve a quadratic equation with one variable using Python.

This article will guide you on how to solve a quadratic equation with one variable ax^2 + bx + c = 0 (a, b != 0) using Python, an equation you learned in 9th grade.

This article will guide you on how to solve a quadratic equation with one variable Picture 1 of Solve a quadratic equation with one variable using Python. using Python, an equation you learned in 9th grade. Before we start writing the program in Python, we must first know how to solve a quadratic equation:

 

How to solve a quadratic equation with one variable

Solving a quadratic equation means finding the values ​​of x such that when x is substituted into the equation, the result is satisfied Picture 2 of Solve a quadratic equation with one variable using Python. .

Step 1: Calculate Δ=b 2 -4ac

Step 2: Compare Δ with 0

  1. Δ < 0 => equation (1) has no solution
  2. Δ = 0 => equation (1) has a double root Picture 3 of Solve a quadratic equation with one variable using Python.
  3. Δ > 0 => equation (1) has 2 distinct solutions, we use the following solution formula :

Picture 4 of Solve a quadratic equation with one variable using Python. and Picture 5 of Solve a quadratic equation with one variable using Python.

 

Solve quadratic equations with one variable using Python.

Step 1 : Allow the user to input three numbers: a, b, c, with the condition that a and b ≠ 0.

Step 2 : Calculate Delta (Δ)

Step 3 : Based on the analysis of the quadratic equation above, we can use the following formula to calculate the roots of the quadratic equation:

x = (-b ± sqrt(b^2 - 4ac)) / 2a where  sqrt() is the function for calculating the square root.

Python code to solve a quadratic equation with one variable:

import math print("Giải phương trình bậc 2: ax2 + bx + c = 0 (a, b khác 0)") print("Bạn đang làm bài tập Python trên QuanTriMang") print("============") # Nhập số a, b và kiểm tra điều kiện khác 0 a = float(input("Mời bạn nhập hệ số a: ")) while True: if a == 0: a = float(input("Số a phải khác 0. Mời nhập lại số a: ")) else: break b = float(input("Mời bạn nhập hệ số b: ")) while True: if b == 0: b = float(input("Số b phải khác 0. Mời nhập lại số b: ")) else: break # Nhập số c c = float(input("Mời bạn nhập hệ số c: ")) # Tính Delta delta = b**2 - 4 * a * c # Tìm nghiệm của phương trình if delta < 0: print("Phương trình vô nghiệm") elif delta == 0: print("Phương trình có nghiệm kép x1 = x2 = ", -(b / (2 * a)) ) else: print("Phương trình có hai nghiệm phân biệt:") print("x1 = ", (-(b) + math.sqrt(delta))/(2*a) ) print("x2 = ", (-(b) - math.sqrt(delta))/(2*a) )

Try running the code above using QuanTriMang's Python Online tool and see the results! Here are some examples you can try:

  1. Picture 6 of Solve a quadratic equation with one variable using Python. (a=1, b=-3, c=2)
  2. Picture 7 of Solve a quadratic equation with one variable using Python. (a=1, b=1, c=-6)
« PREV POST
READ NEXT »