Post Reply 
HP50G Bisection methode
10-03-2020, 02:03 AM
Post: #6
RE: HP50G Bisection methode
Hi, acser.

Welcome to the forum.
Your code had a few bugs. Example, what happens if F(C) = 0 ?

Also, we can reduce 4 functions calls per loop down to 1
Bonus: this avoided underflow issue, when F(A)*F(C) = 0.0, losing sign info.

Code:
def solve_bisect(f,a,b, eps=1e-8, verbal=True):
    fa, fb = f(a), f(b)
    if fa==0: return a
    if fb==0: return b
    if fa > fb: a, fa, b, fb = b, fb, a, fa
    assert fa < 0 and fb > 0, "bad interval"
    while abs(a-b) > eps:
        if verbal: print a, b
        c = (a+b)/2
        fc = f(c)
        if fc <= 0: a=c
        if fc >= 0: b=c
    return (a+b)/2

>>> f = lambda x: x**5 - 5
>>> solve_bisect(f,0,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in solve_bisect
AssertionError: bad interval

>>> solve_bisect(f,1,2)
1 2
1 1.5
1.25 1.5
1.375 1.5
1.375 1.4375
1.375 1.40625
1.375 1.390625
1.375 1.3828125
1.37890625 1.3828125
...
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
HP50G Bisection methode - tigger - 07-24-2015, 12:01 PM
RE: HP50G Bisection methode - Gilles - 07-24-2015, 04:35 PM
RE: HP50G Bisection methode - Namir - 07-29-2015, 11:37 AM
RE: HP50G Bisection methode - Namir - 07-29-2015, 11:31 AM
RE: HP50G Bisection methode - acser - 10-02-2020, 11:30 PM
RE: HP50G Bisection methode - Albert Chan - 10-03-2020 02:03 AM
RE: HP50G Bisection methode - Albert Chan - 10-04-2020, 03:04 PM
RE: HP50G Bisection methode - acser - 10-07-2020, 09:15 PM
RE: HP50G Bisection methode - John Keith - 10-08-2020, 11:55 AM
RE: HP50G Bisection methode - acser - 10-08-2020, 12:55 PM



User(s) browsing this thread: 1 Guest(s)