1
+ '''
2
+ Tests the approximate definite integral functions provided in jmath.approximation
3
+ '''
4
+
5
+ # - Imports
6
+
7
+ from .tools import random_integer , repeat
8
+ from ..jmath .approximation import trapezium_rule , right_hand_rule , left_hand_rule
9
+
10
+ # - Tests
11
+
12
+ @repeat
13
+ def test_on_increasing_func ():
14
+ """Tests that on an increasing linear function the left hand rule underestimates, the right hand rule over estimates, and trapezium rule is exact"""
15
+ coeffecient = random_integer (1 , 100 )
16
+ linear_function = lambda x : coeffecient * x
17
+ lower_bound = random_integer (0 , 98 )
18
+ upper_bound = random_integer (lower_bound + 1 , 100 )
19
+ samples = upper_bound - lower_bound
20
+
21
+ # Find exact area since it is linear
22
+ exact_area = 0.5 * upper_bound * linear_function (upper_bound ) - 0.5 * lower_bound * linear_function (lower_bound )
23
+
24
+ # Use approximations
25
+ trapezium_area = trapezium_rule (linear_function , lower_bound , upper_bound , samples )
26
+ left_area = left_hand_rule (linear_function , lower_bound , upper_bound , samples )
27
+ right_area = right_hand_rule (linear_function , lower_bound , upper_bound , samples )
28
+
29
+ # Assert trapezium and exact match to 5 dp
30
+ assert round (trapezium_area , 5 ) == round (exact_area , 5 )
31
+
32
+ # Assert left less than trapezium less than right
33
+ assert left_area < trapezium_area < right_area
34
+
35
+ @repeat
36
+ def test_on_decreasing_func ():
37
+ """Tests that on a decreasing linear function the left hand rule overestimates, the right hand rule underestimates, and trapezium rule is exact"""
38
+ coeffecient = random_integer (- 100 , - 1 )
39
+ linear_function = lambda x : coeffecient * x
40
+ lower_bound = random_integer (0 , 98 )
41
+ upper_bound = random_integer (lower_bound + 1 , 100 )
42
+ samples = upper_bound - lower_bound
43
+
44
+ # Find exact area since it is linear
45
+ exact_area = 0.5 * upper_bound * linear_function (upper_bound ) - 0.5 * lower_bound * linear_function (lower_bound )
46
+
47
+ # Use approximations
48
+ trapezium_area = trapezium_rule (linear_function , lower_bound , upper_bound , samples )
49
+ left_area = left_hand_rule (linear_function , lower_bound , upper_bound , samples )
50
+ right_area = right_hand_rule (linear_function , lower_bound , upper_bound , samples )
51
+
52
+ # Assert trapezium and exact match to 5 dp
53
+ assert round (trapezium_area , 5 ) == round (exact_area , 5 )
54
+
55
+ # Assert left moe than trapezium more than right
56
+ assert left_area > trapezium_area > right_area
0 commit comments