05/31 Q.Pythonデジタル資料型

3453 ワード

Q)Pythonにルートの公式を書く.

import math

class NonQuadraticError(Exception):
    def __str__(self):
        return "Coefficient 'a' must not be zero"

def quadraticFormula(a, b, c):
    if not a:
        raise NonQuadraticError
        
    D = b**2 - 4*a*c
    
    if D > 0:
        x1 = (-b + math.sqrt(D)) / 2*a
        x2 = (-b - math.sqrt(D)) / 2*a
        return (x1, x2)
    elif not D:
        return (-b / 2*a)
    else:
        print("Imaginary Number")