Python 二次方程求根器

使用 Python 中的判別式求解二次方程式並辨識實數根和複數根。

在編輯器中嘗試

概述

二次方程式的形式為 ax² + bx + c = 0。解方程式需要二次公式:「x = (-b ± sqrt(b² - 4ac)) / 2a」。

術語“b² - 4ac”稱為判別式。如果为正,则有两个不同的实根。若為零,則為一個實根。如果为负,则为两个复根。

Python 內建的 cmath 模組支援複數,即使判別式為負,我們也能找到根。

程式碼和執行輸出

強大的解算器能夠處理實數、零和複數判別式。

import cmath

def find_roots(a, b, c):
    d = (b**2) - (4*a*c) # discriminant
    
    # Calculate both roots
    sol1 = (-b - cmath.sqrt(d)) / (2*a)
    sol2 = (-b + cmath.sqrt(d)) / (2*a)
    
    return sol1, sol2

# Test equation: x^2 - 5x + 6 = 0
r1, r2 = find_roots(1, -5, 6)
print("Roots of x^2 - 5x + 6 = 0:")
print(f"Root 1: {r1.real:.1f}")
print(f"Root 2: {r2.real:.1f}")
端子輸出
Roots of x^2 - 5x + 6 = 0:
Root 1: 2.0
Root 2: 3.0

逐步實施

  • 物理模型和轨迹跟踪系统
  • 幾何碰撞檢測向量
  • 數學求解器

常見問題解答

为什么使用“cmath”而不是“math”?

如果您嘗試計算負數的平方根,標準「math」模組將引發 ValueError。 「cmath」(複數數學)模組會自動處理虛根。

相關主題