12
12
* \f$\lambda\f$ : rate parameter
13
13
*/
14
14
15
- #include < cassert> // For assert
16
- #include < cmath> // For std::pow
17
- #include < iostream> // For I/O operation
15
+ #include < cassert> // For assert
16
+ #include < cmath> // For std::pow
17
+ #include < iostream> // For I/O operation
18
+ #include < stdexcept> // For std::invalid_argument
19
+ #include < string> // For std::string
18
20
19
21
/* *
20
22
* @brief the expected value of the exponential distribution
21
23
* @returns \f[\mu = \frac{1}{\lambda}\f]
22
24
*/
23
25
double exponential_expected (double lambda) {
24
26
if (lambda <= 0 ) {
25
- std::cout << " Error: Lambda must be greater than 0." << ' \n ' ;
26
- assert (lambda > 0 );
27
+ throw std::invalid_argument (" lambda must be greater than 0" );
27
28
}
28
29
return 1 / lambda;
29
30
}
@@ -34,8 +35,7 @@ double exponential_expected(double lambda) {
34
35
*/
35
36
double exponential_var (double lambda) {
36
37
if (lambda <= 0 ) {
37
- std::cout << " Error: Lambda must be greater than 0." << ' \n ' ;
38
- assert (lambda > 0 );
38
+ throw std::invalid_argument (" lambda must be greater than 0" );
39
39
}
40
40
return 1 / pow (lambda, 2 );
41
41
}
@@ -46,8 +46,7 @@ double exponential_var(double lambda) {
46
46
*/
47
47
double exponential_std (double lambda) {
48
48
if (lambda <= 0 ) {
49
- std::cout << " Error: Lambda must be greater than 0." << ' \n ' ;
50
- assert (lambda > 0 );
49
+ throw std::invalid_argument (" lambda must be greater than 0" );
51
50
}
52
51
return 1 / lambda;
53
52
}
@@ -72,6 +71,9 @@ static void test() {
72
71
double var_3 = 0.111111 ;
73
72
double std_3 = 0.333333 ;
74
73
74
+ double lambda_4 = 0 ; // Test 0
75
+ double lambda_5 = -2.3 ; // Test negative value
76
+
75
77
const float threshold = 1e-3f ;
76
78
77
79
std::cout << " Test for lambda = 1 \n " ;
@@ -90,7 +92,27 @@ static void test() {
90
92
assert (std::abs (expected_3 - exponential_expected (lambda_3)) < threshold);
91
93
assert (std::abs (var_3 - exponential_var (lambda_3)) < threshold);
92
94
assert (std::abs (std_3 - exponential_std (lambda_3)) < threshold);
93
- std::cout << " ALL TEST PASSED\n " ;
95
+ std::cout << " ALL TEST PASSED\n\n " ;
96
+
97
+ std::cout << " Test for lambda = 0 \n " ;
98
+ try {
99
+ exponential_expected (lambda_4);
100
+ exponential_var (lambda_4);
101
+ exponential_std (lambda_4);
102
+ } catch (std::invalid_argument& err) {
103
+ assert (std::string (err.what ()) == " lambda must be greater than 0" );
104
+ }
105
+ std::cout << " ALL TEST PASSED\n\n " ;
106
+
107
+ std::cout << " Test for lambda = -2.3 \n " ;
108
+ try {
109
+ exponential_expected (lambda_5);
110
+ exponential_var (lambda_5);
111
+ exponential_std (lambda_5);
112
+ } catch (std::invalid_argument& err) {
113
+ assert (std::string (err.what ()) == " lambda must be greater than 0" );
114
+ }
115
+ std::cout << " ALL TEST PASSED\n\n " ;
94
116
}
95
117
96
118
/* *
0 commit comments