import sys from math import * def bisection_root_solver(f, a, b, n=10): ''' To apply the cml-arguments: f = sys.argv[1] a = int(sys.argv[2]) b = int(sys.argv[3]) ''' sign_a = -1 if compute(f(a)) < 0 else 1 sign_b = -1 if compute(f(b)) < 0 else 1 for i in range(n): m = (a-b)/float(n) sign_m = -1 if compute(f(m)) < 0 else 1 if sign_a != sign_m: b = m sign_b = sign_m elif sign_b != sign_m: a = m sign_a = sign_m print ('%s has a root in [%3f, %3f])' % (f, a, b) def compute(f): code = ''' def f(x): return %s ''' % f exec(code) bisection_root_solver('cos(pi*x)', 0, 0.82)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question