LoginSignup
5
5

More than 5 years have passed since last update.

Python3で2次方程式を解くには

Last updated at Posted at 2018-04-18

Python3で2次方程式を解くには

2次方程式とは

一般的に $ ax^2 + bx + c = 0$ のように表されます。
これを解くには、2次方程式の解の公式を思い出します。

2次方程式の解の公式

$x_1=\frac{-b+\sqrt{b^2-4ac}}{2a}$ と $x_2=\frac{-b-\sqrt{b^2-4ac}}{2a}$

2次方程式は2つの解を持ちます。
と言うことは、方程式の両辺を等しくする$x$の値が2つあることになります。
(その2つが同じということもあり得ます)

pythonで解いてみる

# solving a quadratic equation

def solv_quadratic_equation(a, b, c):
    """ 2次方程式を解く  """
    D = (b**2 - 4*a*c) ** (1/2)
    x_1 = (-b + D) / (2 * a)
    x_2 = (-b - D) / (2 * a)

    return x_1, x_2

if __name__ == '__main__':
    a =input('input a: ')
    b =input('input b: ')
    c =input('input c: ')

    print(solv_quadratic_equation.__doc__)
    x1, x2 = solv_quadratic_equation(float(a) , float(b) , float(c))

    print('x1:{}'.format(x1))
    print('x2:{}'.format(x2))

例1

こちらは解が2つとも数値で返る例

$ x^2 + 2x + 1 = 0$

input a: 1
input b: 2
input c: 1
 2次方程式を解く  
x1:-1.0
x2:-1.0

例2

こちらは解が複素数で返る例

$ x^2 + 2x + 3 = 0$

input a: 1
input b: 2
input c: 3
 2次方程式を解く  
x1:(-0.9999999999999999+1.4142135623730951j)
x2:(-1-1.4142135623730951j)
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5