-
Notifications
You must be signed in to change notification settings - Fork 7
/
calculus.py
106 lines (84 loc) · 2.38 KB
/
calculus.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import unittest
import calculus
class CalculusTests(unittest.TestCase):
def test_simpson(self):
"""
Tests the simpson function with a simple function f(x) = x^2.
"""
# Test with a simple function
f = lambda x: x**2
a = 0
b = 1
n = 2
result = calculus.simpson(f, a, b, n)
self.assertEqual(result, 1.0 / 3)
def test_trapezoid(self):
"""
Tests the trapezoid function with a simple function f(x) = x^2.
"""
# Test with a simple function
f = lambda x: x**2
a = 0
b = 1
n = 2
result = calculus.trapezoid(f, a, b, n)
self.assertEqual(result, 2.0 / 3)
def test_adaptive_trapezoid(self):
"""
Tests the adaptive_trapezoid function with a simple function f(x) = x^2.
"""
# Test with a simple function
f = lambda x: x**2
a = 0
b = 1
acc = 1.0e-6
result = calculus.adaptive_trapezoid(f, a, b, acc)
self.assertEqual(result, 1.0 / 3)
def test_root_simple(self):
"""
Tests the root_simple function with a simple function f(x) = x^2 - 4.
"""
# Test with a simple function
f = lambda x: x**2 - 4
x = 2
dx = 1
accuracy = 1.0e-6
root, iterations = calculus.root_simple(f, x, dx, accuracy)
self.assertEqual(root, 2.0)
self.assertEqual(len(iterations), 1)
def test_root_bisection(self):
"""
Tests the root_bisection function with a simple function f(x) = x^2 - 4.
"""
# Test with a simple function
f = lambda x: x**2 - 4
x1 = 1
x2 = 3
accuracy = 1.0e-6
root, iterations = calculus.root_bisection(f, x1, x2, accuracy)
self.assertEqual(root, 2.0)
self.assertEqual(len(iterations), 3)
def test_root_secant(self):
"""
Tests the root_secant function with a simple function f(x) = x^2 - 4.
"""
# Test with a simple function
f = lambda x: x**2 - 4
x0 = 1
x1 = 3
accuracy = 1.0e-6
root, iterations = calculus.root_secant(f, x0, x1, accuracy)
self.assertEqual(root, 2.0)
self.assertEqual(len(iterations), 2)
def test_root_tangent(self):
"""
Tests the root_tangent function with a simple function f(x) = x^2 - 4.
"""
# Test with a simple function
f = lambda x: x**2 - 4
fp = lambda x: 2*x
x0 = 1
accuracy = 1.0e-6
root, iterations = calculus.root_tangent(f, fp, x0, accuracy)
self.assertEqual(root, 2.0)
self.assertEqual(len(iterations), 2)