forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbisection.py
More file actions
Latest commit
55 lines (47 loc) · 1.63 KB
/
Copy pathbisection.py
File metadata and controls
55 lines (47 loc) · 1.63 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
fromcollections.abcimportCallable
defbisection(function: Callable[[float], float], a: float, b: float) ->float:
"""
finds where function becomes 0 in [a,b] using bolzano
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
1.0000000149011612
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
1.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
3.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
"""
start: float=a
end: float=b
iffunction(a) ==0: # one of the a or b is a root for the function
returna
eliffunction(b) ==0:
returnb
elif (
function(a) *function(b) >0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raiseValueError("could not find root in given interval.")
else:
mid: float=start+ (end-start) /2.0
whileabs(start-mid) >10**-7: # until precisely equals to 10^-7
iffunction(mid) ==0:
returnmid
eliffunction(mid) *function(start) <0:
end=mid
else:
start=mid
mid=start+ (end-start) /2.0
returnmid
deff(x: float) ->float:
returnx**3-2*x-5
if__name__=="__main__":
print(bisection(f, 1, 1000))
importdoctest
doctest.testmod()