- Notifications
You must be signed in to change notification settings - Fork 296
/
Copy pathnewton_test.py
62 lines (43 loc) · 1.42 KB
/
newton_test.py
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
56
57
58
59
60
61
62
fromitertoolsimporttakewhile
fromassertpyimportassert_that
fromnewtonimportnewton_sequence
EPSILON=1e-4
deftest_newtons_sequence_converge():
deff(x):
returnx**5-x-1
deff_derivative(x):
return5*x**4-1
starting_x=1
approximation= [
(x, f(x))
forxinlist(newton_sequence(f, f_derivative, starting_x))
]
assert_that(approximation[-1][0]).is_close_to(1.1673, EPSILON)
assert_that(approximation[-1][1]).is_close_to(0, EPSILON)
deftest_newtons_sequence_fails_to_converge():
deff(x):
returnx**5-x-1
deff_derivative(x):
return5*x**4-1
starting_x=0
approximation= [
(x, f(x)) for (i, x) intakewhile(
lambdaz: z[0] <10000,
enumerate(newton_sequence(f, f_derivative, starting_x))
)
]
for (x, y) inapproximation:
assert_that(abs(x-1.1673)).is_greater_than(EPSILON)
assert_that(abs(y)).is_greater_than(EPSILON)
deftest_newtons_sequence_converges_large_root():
deff(x):
return (x-100)**5- (x-100) -1
deff_derivative(x):
return5* (x-100)**4-1
starting_x=103
approximation= [
(x, f(x))
forxinlist(newton_sequence(f, f_derivative, starting_x))
]
assert_that(approximation[-1][0]).is_close_to(101.1673, EPSILON)
assert_that(approximation[-1][1]).is_close_to(0, EPSILON)