Python-二次方程式ax ^ 2 + bx + c = 0の2つの解を見つける

大きな牛の人工知能のチュートリアルを共有します。ゼロベース!わかりやすい!面白くてユーモラス!あなたも人工知能チームに参加してください!http://www.captainbed.netをクリックしてください

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import math

A = float(input('a = '))
B = float(input('b = '))
C = float(input('c = '))


def quadratic(a, b, c):
    for i in (a, b, c):
        if not isinstance(i, (int, float)):
            raise TypeError("Wrong argument type!")
    if a == 0:
        if b != 0:
            x = -c / b
            return x
        else:
            return "No solution!"
    else:
        delta = b * b - 4 * a * c
        if delta >= 0:
            x1 = (-b + math.sqrt(delta)) / (2 * a)
            x2 = (-b - math.sqrt(delta)) / (2 * a)
            if x1 == x2:
                return x1
            else:
                return x1, x2
        else:
            return "No solution!"


print(quadratic(A, B, C))

# Test
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))

if quadratic(2, 3, 1) != (-0.5, -1.0):
    print('Test FAIL!')
elif quadratic(1, 3, -4) != (1.0, -4.0):
    print('Test FAIL!')
else:
    print('Test PASS~')

 

おすすめ

転載: blog.csdn.net/chimomo/article/details/109852853