Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active February 26, 2018 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/8c42cc11a59cc0657bee6f4ca91dacaf to your computer and use it in GitHub Desktop.
Save komasaru/8c42cc11a59cc0657bee6f4ca91dacaf to your computer and use it in GitHub Desktop.
Python script to compute nonlinear equation with bisection method.
#! /usr/local/bin/python3.6
"""
Nonlinear equation with bisection method
"""
import sys
import traceback
class NonlinearEquation:
EPS = 1e-08 # Precision of truncation
LIMIT = 50 # Number of truncation
def __init__(self):
self.f = lambda x: x**3 - x + 1
def compute(self):
"""
Computation of nonlinear equation with bisection method
"""
try:
low, high = -2.0, 2.0
cnt_loop = 0
for k in range(1, self.LIMIT + 1):
cnt_loop = k
x = (low + high) / 2
if self.f(x) > 0:
high = x
else:
low = x
if self.f(x) == 0 or abs(high - low) / abs(low) < self.EPS:
print("x = {:f}".format(x))
break
if cnt_loop == self.LIMIT:
print("収束しない")
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = NonlinearEquation()
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