Table of Contents
This article will guide you on how to solve a quadratic equation with one variable
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
.
Step 1: Calculate ?=b 2 -4ac
Step 2: Compare ? with 0
- ? < 0 => equation (1) has no solution
- ? = 0 => equation (1) has a double root
- ? > 0 => equation (1) has 2 distinct solutions, we use the following solution formula :
and
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 tipsmake") 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 tipsmake's Python Online tool and see the results! Here are some examples you can try:
-
(a=1, b=-3, c=2)
-
(a=1, b=1, c=-6)
Reader Comments 0
Sign in with email or Google to join the discussion.