import math func_glob lambda 10 func_first lambda a1 -9 b1 -1 a2 -2 b2

 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
import math
func_glob = lambda x: x ** 3 + 3 * x ** 2 - 4 * x + 10
func_first = lambda x: 3 * x ** 2 + 6 * x - 4
a1 = -9.
b1 = -1.
a2 = -2.
b2 = 2.
a3 = 2.
b3 = 6.
e = 0.001
def half_divide_method(a, b, f):
x = (a + b) / 2
while math.fabs(f(x)) >= e:
x = (a + b) / 2
if f(a) * f(x) < 0:
b = x
else:
a = x
return (a + b) / 2
def newtons_method(a, b, f, f1):
x0 = (a + b) / 2
x1 = x0 - (f(x0) / f1(x0))
while True:
if math.fabs(x1 - x0) < e:
return x1
x0 = x1
x1 = x0 - (f(x0) / f1(x0))
print '%s | %s' % \
(half_divide_method(a1, b1, func_glob), newtons_method(a1, b1, func_glob, func_first))
print '%s | %s' % \
(half_divide_method(a2, b2, func_glob), newtons_method(a2, b2, func_glob, func_first))
print '%s | %s' % \
(half_divide_method(a3, b3, func_glob), newtons_method(a3, b3, func_glob, func_first))