Discuss / Python / 解二次方程

解二次方程

Topic source
# -*- coding: utf-8 -*-

import cmath
import math

def quadratic(a, b, c):
    t = b * b - 4 * a * c
    if t == 0:
        return -b / (2 * a)
    elif t > 0:
        t = math.sqrt(t)
    else:
        t = cmath.sqrt(t)
    x1 = (-b + t) / (2 * a)
    x2 = (-b - t) / (2 * a)
    return x1, x2

print(quadratic(4, 1, 4)) # => ((-0.125+0.9921567416492215j), (-0.125-0.9921567416492215j))
print(quadratic(2, 3, 1)) # => (-0.5, -1.0)
print(quadratic(1, 3, -4)) # => (1.0, -4.0)

  • 1

Reply