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
107
108
//! The utilies module provides general capabilities, that may span the
//! input modeling, models, output analysis, and simulator modules. The
//! utilities are centered around debugging/traceability and common
//! arithmetic.
use SimulationError;
/// The function evaluates a polynomial at a single value, with coefficients
/// defined as a slice, from the highest polynomial order to the zero order.
/// Horner's method is used for this polynomial evaluation
/// For example for the polynomial:
///
/// 2x^4 - 3x^3 + x^2 - 2x + 3
///
/// the coefficients would be presented as
/// ```rust,ignore
/// vec![2.0, -3.0, 1.0, -2.0, 3.0]
/// ```
///
/// ```
/// use sim::utils::evaluate_polynomial;
/// let coefficients = vec![2.0, -3.0, 1.0, -2.0, 3.0];
/// let x: f64 = 44.0;
/// let actual_y = evaluate_polynomial(&coefficients, x).ok().unwrap();
/// let expected_y = (2.0 * x.powf(4.0))
/// + (-3.0 * x.powf(3.0))
/// + (1.0 * x.powf(2.0))
/// + (-2.0 * x.powf(1.0))
/// + (3.0 * x.powf(0.0));
/// assert_eq!(actual_y, expected_y);
/// ```
/// Horner Algorithm for polynomial evaluation
/// It is expected that the coefficients are ordered from least significant to most significant.
/// For example for the polynomial:
///
/// 2x^4 -3x^3 + x^2 -2x + 3
///
/// the coefficients would be presented as
///
/// ```rust,ignore
/// vec![3.0, -2.0, 1.0, -3.0, 2.0]
/// ```
///
/// ```
/// use sim::utils::horner_fold;
/// let coefficients = vec![3.0, -2.0, 1.0, -3.0, 2.0];
/// let x: f64 = 2.0;
/// let actual_y = horner_fold(&coefficients, x);
/// let expected_y = (2.0 * x.powf(4.0))
/// + (-3.0 * x.powf(3.0))
/// + (1.0 * x.powf(2.0))
/// + (-2.0 * x.powf(1.0))
/// + (3.0 * x.powf(0.0));
/// assert_eq!(actual_y, expected_y);
/// ```
/// When the `console_error_panic_hook` feature is enabled, we can call the
/// `set_panic_hook` function at least once during initialization, and then
/// we will get better error messages if our code ever panics.
///
/// For more details see
/// <https://github.com/rustwasm/console_error_panic_hook#readme>
/// Integer square root calculation, using the Babylonian square-root
/// algorithm.