Last active
October 3, 2022 09:45
-
-
Save komasaru/20ba36a7c3d7f2a50622eceee6965f08 to your computer and use it in GitHub Desktop.
Python script to compute nonlinear equation with Newton method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment