Wurzelfinder für quadratische Python-Gleichung

Lösen Sie quadratische Gleichungen und identifizieren Sie reelle und komplexe Wurzeln mithilfe der Diskriminanzformel in Python.

Versuchen Sie es im Editor

Übersicht

Eine quadratische Gleichung hat die Form ax² + bx + c = 0. Um sie zu lösen, ist die quadratische Formel „x = (-b ± sqrt(b² - 4ac)) / 2a“ erforderlich.

Der Begriff „b² – 4ac“ wird als Diskriminante bezeichnet. Wenn positiv, gibt es zwei unterschiedliche reelle Wurzeln. Wenn Null, eine echte Wurzel. Wenn negativ, zwei komplexe Wurzeln.

Das integrierte „cmath“-Modul von Python unterstützt komplexe Zahlen und ermöglicht es uns, Wurzeln zu finden, selbst wenn die Diskriminante negativ ist.

Code- und Ausführungsausgabe

Robuster Löser, der reelle, Null- und komplexe Diskriminanten verarbeiten kann.

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}")
Terminal-Ausgabe
Roots of x^2 - 5x + 6 = 0:
Root 1: 2.0
Root 2: 3.0

Schrittweise Umsetzung

  • Physikmodelle und Flugbahnverfolgungssysteme
  • Geometrische Kollisionserkennungsvektoren
  • Mathematische Löser

Häufig gestellte Fragen

Warum „cmath“ anstelle von „math“ verwenden?

Das Standardmodul „math“ löst einen ValueError aus, wenn Sie versuchen, die Quadratwurzel einer negativen Zahl zu ziehen. Das Modul „cmath“ (komplexe Mathematik) verarbeitet automatisch imaginäre Wurzeln.

Verwandte Themen