Python - 非線形方程式の解法(ニュートン法)!

Updated:


Python 3 で非線形方程式をニュートン法を使用して解く方法についての記録です。

0. 前提条件

  • LMDE 2 (Linux Mint Debian Edition 2; 64bit) での作業を想定。
  • Python 3.6.4 での作業を想定。
  • 当方は他のバージョンとの共存環境であり、 python3.6, pip3.6 で 3.6 系を使用するようにしている。(適宜、置き換えて考えること)

1. アルゴリズムについて

当ブログ過去記事を参照。

2. Python スクリプトの作成

  • 敢えてオブジェクト指向で作成している。
  • Shebang ストリング(1行目)では、フルパスでコマンド指定している。(当方の慣習
  • 必要であれば、スクリプト内の定数や関数を変更する。

File: nonlinear_equation_newton.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#! /usr/local/bin/python3.6
"""
Nonlinear equation with Newton method
"""
import sys
import traceback


class NonlinearEquationNewton:
    EPS = 1e-08  # Precision of truncation
    LIMIT = 50   # Number of truncation

    def __init__(self):
        self.f = lambda x: x**3 - x + 1
        self.g = lambda x: 3 * x**2 - 1

    def compute(self):
        """
        Computation of nonlinear equation with bisection method
        """
        try:
            x = -2.0
            cnt_loop = 0
            for k in range(1, self.LIMIT + 1):
                cnt_loop = k
                dx = x
                x -= self.f(x) / self.g(x)
                if abs(x - dx) / abs(dx) < self.EPS:
                    print("x = {:f}".format(x))
                    break
            if cnt_loop == self.LIMIT:
                print("収束しない")
        except Exception as e:
            raise


if __name__ == '__main__':
    try:
        obj = NonlinearEquationNewton()
        obj.compute()
    except Exception as e:
        traceback.print_exc()
        sys.exit(1)

3. Python スクリプトの実行

まず、実行権限を付与。

$ chmod +x nonlinear_equation_newton.py

そして、実行。

$ ./nonlinear_equation_newton.py
x = -1.324718

以上





 

Sponsored Link

 

Comments