suspect_machines 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,454 @@
1
+ #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
3
+ #![doc = include_str!("../README.md")]
4
+
5
+ #[cfg(test)]
6
+ extern crate std;
7
+
8
+ mod detector;
9
+ mod math;
10
+ mod roster;
11
+ #[cfg(test)]
12
+ mod test_support;
13
+ mod window;
14
+
15
+ use core::time::Duration;
16
+
17
+ pub use detector::Detector;
18
+ pub use roster::{Forgetting, Roster, Scan, Suspect};
19
+
20
+ /// The distribution the detector assumes heartbeat intervals follow. This is
21
+ /// an assumption the caller makes about its network, not something the
22
+ /// detector verifies.
23
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24
+ pub enum Distribution {
25
+ /// Intervals are normally distributed around the window mean, as in
26
+ /// Hayashibara et al., with the deviation floor of [`Normal`].
27
+ Normal(Normal),
28
+ /// Intervals are exponentially distributed with the window mean. Only the
29
+ /// mean is used: `phi = silence / (mean * ln 10)`.
30
+ Exponential,
31
+ }
32
+
33
+ /// The normal model's deviation floor: the window's population standard
34
+ /// deviation is floored at `min_std_dev`, so a perfectly regular sender does
35
+ /// not make the first late nanosecond infinitely suspicious.
36
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
37
+ pub struct Normal {
38
+ floor_ns: u64,
39
+ }
40
+
41
+ impl Normal {
42
+ /// A normal model floored at `min_std_dev`.
43
+ ///
44
+ /// # Errors
45
+ ///
46
+ /// [`ConfigError::ZeroDeviationFloor`] for a zero floor and
47
+ /// [`ConfigError::DurationOverflow`] past `u64` nanoseconds.
48
+ pub const fn new(min_std_dev: Duration) -> Result<Self, ConfigError> {
49
+ match nanos(min_std_dev) {
50
+ None => Err(ConfigError::DurationOverflow),
51
+ Some(0) => Err(ConfigError::ZeroDeviationFloor),
52
+ Some(floor_ns) => Ok(Self { floor_ns }),
53
+ }
54
+ }
55
+
56
+ /// The non-zero floor for the standard deviation.
57
+ #[must_use]
58
+ pub const fn min_std_dev(self) -> Duration {
59
+ Duration::from_nanos(self.floor_ns)
60
+ }
61
+ }
62
+
63
+ /// Why a configuration was refused.
64
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
65
+ pub enum ConfigError {
66
+ /// A warm-up of zero intervals would report phi from no data.
67
+ ZeroWarmUp,
68
+ /// The normal model needs a non-zero deviation floor.
69
+ ZeroDeviationFloor,
70
+ /// A duration does not fit in `u64` nanoseconds.
71
+ DurationOverflow,
72
+ /// The interval window has no slots.
73
+ ZeroWindow,
74
+ /// The warm-up asks for more intervals than the window can hold.
75
+ WarmUpExceedsWindow,
76
+ }
77
+
78
+ /// Validated detector policy: distribution, warm-up and acceptable pause.
79
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
80
+ pub struct Config {
81
+ distribution: Distribution,
82
+ min_samples: usize,
83
+ pause_ns: u64,
84
+ }
85
+
86
+ impl Config {
87
+ /// A policy that reports phi only once `min_samples` intervals are in the
88
+ /// window, under the given distribution assumption.
89
+ ///
90
+ /// # Errors
91
+ ///
92
+ /// [`ConfigError::ZeroWarmUp`] for zero `min_samples`.
93
+ pub const fn new(distribution: Distribution, min_samples: usize) -> Result<Self, ConfigError> {
94
+ if min_samples == 0 {
95
+ return Err(ConfigError::ZeroWarmUp);
96
+ }
97
+ Ok(Self {
98
+ distribution,
99
+ min_samples,
100
+ pause_ns: 0,
101
+ })
102
+ }
103
+
104
+ /// Tolerates `pause` of extra silence before suspicion starts to accrue:
105
+ /// the pause is added to the expected interval (normal) or subtracted
106
+ /// from the silence (exponential).
107
+ ///
108
+ /// # Errors
109
+ ///
110
+ /// [`ConfigError::DurationOverflow`] when `pause` exceeds `u64`
111
+ /// nanoseconds.
112
+ pub const fn with_acceptable_pause(mut self, pause: Duration) -> Result<Self, ConfigError> {
113
+ match nanos(pause) {
114
+ Some(pause_ns) => {
115
+ self.pause_ns = pause_ns;
116
+ Ok(self)
117
+ }
118
+ None => Err(ConfigError::DurationOverflow),
119
+ }
120
+ }
121
+
122
+ /// The assumed interval distribution.
123
+ #[must_use]
124
+ pub const fn distribution(&self) -> Distribution {
125
+ self.distribution
126
+ }
127
+
128
+ /// Intervals required before phi is reported.
129
+ #[must_use]
130
+ pub const fn min_samples(&self) -> usize {
131
+ self.min_samples
132
+ }
133
+
134
+ /// Extra silence tolerated before suspicion accrues.
135
+ #[must_use]
136
+ pub const fn acceptable_pause(&self) -> Duration {
137
+ Duration::from_nanos(self.pause_ns)
138
+ }
139
+
140
+ /// Checks the policy against a window of `window` intervals.
141
+ const fn fit(self, window: usize) -> Result<Self, ConfigError> {
142
+ if window == 0 {
143
+ return Err(ConfigError::ZeroWindow);
144
+ }
145
+ if self.min_samples > window {
146
+ return Err(ConfigError::WarmUpExceedsWindow);
147
+ }
148
+ Ok(self)
149
+ }
150
+
151
+ /// Phi for `silence_ns` without a heartbeat, given the window statistics.
152
+ fn phi(&self, statistics: &Statistics, silence_ns: u64) -> Phi {
153
+ let silence = window::to_f64(silence_ns);
154
+ let pause = window::to_f64(self.pause_ns);
155
+ Phi(match self.distribution {
156
+ Distribution::Normal(normal) => {
157
+ let floor = window::to_f64(normal.floor_ns);
158
+ let deviation = if statistics.std_dev_ns > floor {
159
+ statistics.std_dev_ns
160
+ } else {
161
+ floor
162
+ };
163
+ math::normal_phi((silence - statistics.mean_ns - pause) / deviation)
164
+ }
165
+ Distribution::Exponential => {
166
+ math::exponential_phi((silence - pause) / statistics.mean_ns)
167
+ }
168
+ })
169
+ }
170
+ }
171
+
172
+ /// Why a call was refused. A refused call changes nothing.
173
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
174
+ pub enum Refusal {
175
+ /// `now` is earlier than the last recorded heartbeat.
176
+ TimeRegression,
177
+ /// `now` equals the last recorded heartbeat: a zero interval carries no
178
+ /// timing information and is not recorded.
179
+ SameInstant,
180
+ /// `now` does not fit in `u64` nanoseconds.
181
+ Overflow,
182
+ /// The heartbeat carries an incarnation older than the tracked one.
183
+ Stale,
184
+ /// Every roster slot tracks another peer.
185
+ Full,
186
+ /// The roster does not track this peer.
187
+ Untracked,
188
+ }
189
+
190
+ impl core::fmt::Display for Refusal {
191
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
192
+ f.write_str(match self {
193
+ Self::TimeRegression => "the instant precedes the last recorded heartbeat",
194
+ Self::SameInstant => "the instant equals the last recorded heartbeat",
195
+ Self::Overflow => "the instant does not fit in 64-bit nanoseconds",
196
+ Self::Stale => "the incarnation is older than the tracked one",
197
+ Self::Full => "every roster slot tracks another peer",
198
+ Self::Untracked => "the roster does not track this peer",
199
+ })
200
+ }
201
+ }
202
+
203
+ impl core::error::Error for Refusal {}
204
+
205
+ /// What an accepted heartbeat did.
206
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
207
+ pub enum Beat {
208
+ /// First heartbeat: a reference point, no interval yet.
209
+ First,
210
+ /// An interval entered the window, evicting the oldest one when full.
211
+ Recorded {
212
+ /// Time since the previous heartbeat.
213
+ interval: Duration,
214
+ /// Intervals now in the window.
215
+ samples: usize,
216
+ },
217
+ /// A newer incarnation replaced the tracked one; its statistics start
218
+ /// over from this heartbeat.
219
+ Restarted,
220
+ }
221
+
222
+ impl Beat {
223
+ /// The [`Beat::Recorded`] a window of `W` intervals can answer: `None`
224
+ /// for a zero interval (refused as [`Refusal::SameInstant`]) or a sample
225
+ /// count outside `1..=W`.
226
+ #[must_use]
227
+ pub const fn recorded<const W: usize>(interval: Duration, samples: usize) -> Option<Self> {
228
+ if interval.is_zero() || samples == 0 || samples > W {
229
+ return None;
230
+ }
231
+ Some(Self::Recorded { interval, samples })
232
+ }
233
+ }
234
+
235
+ /// A suspicion level: `-log10` of the probability, under the configured
236
+ /// distribution, that a heartbeat would still arrive after this much silence.
237
+ ///
238
+ /// Phi 1 means roughly a 10 % chance the peer is merely late, phi 3 roughly
239
+ /// 0.1 %. It is a statement about arrival statistics. It is not a verdict
240
+ /// that the peer is dead and it revokes nothing.
241
+ #[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd)]
242
+ pub struct Phi(f64);
243
+
244
+ impl Phi {
245
+ /// `None` unless `value` is finite and not negative. A negative zero is
246
+ /// stored as zero.
247
+ #[must_use]
248
+ pub const fn new(value: f64) -> Option<Self> {
249
+ if value.is_finite() && value >= 0.0 {
250
+ Some(Self(if value == 0.0 { 0.0 } else { value }))
251
+ } else {
252
+ None
253
+ }
254
+ }
255
+
256
+ /// The level as a finite, non-negative `f64`.
257
+ #[must_use]
258
+ pub const fn value(self) -> f64 {
259
+ self.0
260
+ }
261
+
262
+ /// The level in thousandths, rounded down and saturating at `u64::MAX`.
263
+ #[must_use]
264
+ pub const fn millis(self) -> u64 {
265
+ #[allow(
266
+ clippy::cast_possible_truncation,
267
+ clippy::cast_sign_loss,
268
+ reason = "phi is non-negative and float-to-int casts saturate"
269
+ )]
270
+ let millis = (self.0 * 1000.0) as u64;
271
+ millis
272
+ }
273
+
274
+ /// Whether the level has reached `threshold`.
275
+ #[must_use]
276
+ pub fn reaches(self, threshold: Threshold) -> bool {
277
+ self.0 >= threshold.0
278
+ }
279
+ }
280
+
281
+ /// A finite, positive phi level the caller treats as "worth acting on".
282
+ #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
283
+ pub struct Threshold(f64);
284
+
285
+ impl Threshold {
286
+ /// `None` unless `phi` is finite and greater than zero.
287
+ #[must_use]
288
+ pub const fn new(phi: f64) -> Option<Self> {
289
+ if phi.is_finite() && phi > 0.0 {
290
+ Some(Self(phi))
291
+ } else {
292
+ None
293
+ }
294
+ }
295
+
296
+ /// The threshold level.
297
+ #[must_use]
298
+ pub const fn value(self) -> f64 {
299
+ self.0
300
+ }
301
+ }
302
+
303
+ /// What the detector can say about a peer at a given instant.
304
+ #[derive(Debug, Clone, Copy, PartialEq)]
305
+ pub enum Suspicion {
306
+ /// No heartbeat has ever been recorded.
307
+ NoHeartbeat,
308
+ /// Fewer intervals than the configured warm-up: no phi is computed. The
309
+ /// silence is reported so the caller can apply its own bootstrap timeout.
310
+ WarmingUp {
311
+ /// Intervals in the window.
312
+ samples: usize,
313
+ /// Intervals the warm-up requires.
314
+ required: usize,
315
+ /// Time since the last heartbeat.
316
+ silence: Duration,
317
+ },
318
+ /// The suspicion level under the configured distribution.
319
+ Measured(Phi),
320
+ }
321
+
322
+ impl Suspicion {
323
+ /// The [`Suspicion::WarmingUp`] a window of `W` intervals can answer:
324
+ /// `None` unless `samples < required <= W`, since a warm-up is at least
325
+ /// one interval and never longer than the window.
326
+ #[must_use]
327
+ pub const fn warming_up<const W: usize>(
328
+ samples: usize,
329
+ required: usize,
330
+ silence: Duration,
331
+ ) -> Option<Self> {
332
+ if samples >= required || required > W {
333
+ return None;
334
+ }
335
+ Some(Self::WarmingUp {
336
+ samples,
337
+ required,
338
+ silence,
339
+ })
340
+ }
341
+ }
342
+
343
+ /// Statistics of the intervals currently in the window.
344
+ #[derive(Debug, Clone, Copy, PartialEq)]
345
+ pub struct Statistics {
346
+ samples: usize,
347
+ mean_ns: f64,
348
+ std_dev_ns: f64,
349
+ min: Duration,
350
+ max: Duration,
351
+ }
352
+
353
+ impl Statistics {
354
+ /// Statistics a window of `W` intervals can report: `None` unless
355
+ /// `samples` is in `1..=W`, `1 ns <= min <= max` (a zero interval is
356
+ /// never stored, and one interval is its own min and max), the mean lies
357
+ /// within `min..=max`, and the deviation is a finite, positively signed
358
+ /// number no more than half of `max - min` (Popoviciu's bound), all
359
+ /// compared as the `f64` nanoseconds the window computes with.
360
+ #[must_use]
361
+ pub const fn new<const W: usize>(
362
+ samples: usize,
363
+ mean_ns: f64,
364
+ std_dev_ns: f64,
365
+ min: Duration,
366
+ max: Duration,
367
+ ) -> Option<Self> {
368
+ let counted = samples > 0 && samples <= W;
369
+ let ordered = !min.is_zero()
370
+ && min.as_nanos() <= max.as_nanos()
371
+ && (samples > 1 || min.as_nanos() == max.as_nanos());
372
+ let (low, high) = (duration_to_f64(min), duration_to_f64(max));
373
+ let centred = mean_ns >= low && mean_ns <= high;
374
+ let spread = std_dev_ns.is_sign_positive() && std_dev_ns <= half_range(low, high);
375
+ if counted && ordered && centred && spread {
376
+ Some(Self {
377
+ samples,
378
+ mean_ns,
379
+ std_dev_ns,
380
+ min,
381
+ max,
382
+ })
383
+ } else {
384
+ None
385
+ }
386
+ }
387
+
388
+ /// Intervals in the window.
389
+ #[must_use]
390
+ pub const fn samples(&self) -> usize {
391
+ self.samples
392
+ }
393
+
394
+ /// Arithmetic mean, in nanoseconds.
395
+ #[must_use]
396
+ pub const fn mean_ns(&self) -> f64 {
397
+ self.mean_ns
398
+ }
399
+
400
+ /// Population standard deviation, in nanoseconds, before any floor.
401
+ #[must_use]
402
+ pub const fn std_dev_ns(&self) -> f64 {
403
+ self.std_dev_ns
404
+ }
405
+
406
+ /// Shortest interval.
407
+ #[must_use]
408
+ pub const fn min(&self) -> Duration {
409
+ self.min
410
+ }
411
+
412
+ /// Longest interval.
413
+ #[must_use]
414
+ pub const fn max(&self) -> Duration {
415
+ self.max
416
+ }
417
+ }
418
+
419
+ /// A duration's nanoseconds as the nearest `f64`.
420
+ #[allow(
421
+ clippy::cast_precision_loss,
422
+ reason = "nanoseconds round to the nearest f64, as the window computes"
423
+ )]
424
+ pub(crate) const fn duration_to_f64(duration: Duration) -> f64 {
425
+ duration.as_nanos() as f64
426
+ }
427
+
428
+ /// Half the spread between two interval lengths: the largest population
429
+ /// standard deviation intervals within them can have (Popoviciu).
430
+ pub(crate) const fn half_range(low: f64, high: f64) -> f64 {
431
+ (high - low) / 2.0
432
+ }
433
+
434
+ /// `now` as `u64` nanoseconds, or [`Refusal::Overflow`].
435
+ const fn instant(now: Duration) -> Result<u64, Refusal> {
436
+ match nanos(now) {
437
+ Some(now) => Ok(now),
438
+ None => Err(Refusal::Overflow),
439
+ }
440
+ }
441
+
442
+ /// `duration` in nanoseconds when it fits `u64` (about 584 years).
443
+ const fn nanos(duration: Duration) -> Option<u64> {
444
+ let wide = duration.as_nanos();
445
+ if wide > u64::MAX as u128 {
446
+ None
447
+ } else {
448
+ #[allow(clippy::cast_possible_truncation, reason = "range checked above")]
449
+ Some(wide as u64)
450
+ }
451
+ }
452
+
453
+ #[cfg(test)]
454
+ mod tests;
@@ -0,0 +1,229 @@
1
+ //! Deterministic `no_std` elementary functions for the suspicion level.
2
+ //!
3
+ //! `f64::sqrt`, `exp` and `ln` live in `std`, so the detector carries its own.
4
+ //! Every routine uses only IEEE-754 add, subtract, multiply and divide in a
5
+ //! fixed evaluation order with fixed iteration counts: no fused multiply-add,
6
+ //! no platform `libm`, no data-dependent loop exits. The same inputs give the
7
+ //! same bits on every target.
8
+ //!
9
+ //! Error bounds, checked by the crate's tests against `std` and against
10
+ //! 60-digit reference values:
11
+ //!
12
+ //! | routine | domain | bound |
13
+ //! |:--------|:-------|:------|
14
+ //! | [`sqrt`] | finite `x >= 0` | relative `4e-16` |
15
+ //! | [`exp`] | `-708 <= x <= 709` | relative `1e-14` |
16
+ //! | [`ln`] | positive normal `x` | `1e-15` absolute or `1e-14` relative |
17
+ //! | [`normal_phi`] | finite `z` | `1e-12` absolute or `1e-12` relative |
18
+ #![allow(
19
+ clippy::suboptimal_flops,
20
+ clippy::manual_midpoint,
21
+ reason = "plain IEEE operations only: mul_add needs libm on bare metal"
22
+ )]
23
+
24
+ use core::f64::consts::{FRAC_1_SQRT_2, FRAC_2_SQRT_PI, LN_2, LN_10};
25
+
26
+ /// `ln(2 * sqrt(pi))`.
27
+ const LN_2_SQRT_PI: f64 = 1.265_512_123_484_645_4;
28
+ /// Below this `x = |z| / sqrt(2)` the tail comes from the `erf` series; at or
29
+ /// above it, from the continued fraction.
30
+ const SERIES_LIMIT: f64 = 2.0;
31
+ /// Terms of the `erf` series; enough for `x < SERIES_LIMIT`.
32
+ const SERIES_TERMS: u32 = 60;
33
+ /// Levels of the `erfc` continued fraction; enough for `x >= SERIES_LIMIT`.
34
+ const FRACTION_LEVELS: u32 = 60;
35
+ /// Newton steps for `sqrt` from a start within 25 % of the root.
36
+ const NEWTON_STEPS: u32 = 6;
37
+ /// Degree of the `exp` Taylor polynomial on `|r| <= ln(2) / 2`.
38
+ const EXP_DEGREE: u32 = 14;
39
+ /// Terms of the `atanh` series behind `ln`.
40
+ const LN_TERMS: u32 = 13;
41
+ /// Upper bits of `ln(2)`, with enough trailing zeros that multiples up to
42
+ /// `2^10` are exact.
43
+ const LN_2_HIGH: f64 = 6.931_471_803_691_238e-1;
44
+ /// `ln(2) - LN_2_HIGH`.
45
+ const LN_2_LOW: f64 = 1.908_214_929_270_587_7e-10;
46
+ /// The 52 stored mantissa bits of an `f64`.
47
+ const MANTISSA_MASK: u64 = 0x000F_FFFF_FFFF_FFFF;
48
+ /// Width of the stored mantissa: the exponent field starts above it.
49
+ const MANTISSA_BITS: u32 = 52;
50
+ /// Bits of `1.0`: biased exponent zero, empty mantissa.
51
+ const ONE_BITS: u64 = 0x3FF0_0000_0000_0000;
52
+ /// IEEE-754 double exponent bias.
53
+ const EXPONENT_BIAS: i32 = 1023;
54
+ /// Power of two that lifts every subnormal into the normal range.
55
+ const LIFT: i32 = 54;
56
+ /// `2^LIFT`.
57
+ const TWO_54: f64 = 18_014_398_509_481_984.0;
58
+ /// Below this `e^x` underflows to zero (`e^-708` is the last normal result).
59
+ const EXP_FLOOR: f64 = -708.0;
60
+ /// Above this `e^x` overflows to infinity.
61
+ const EXP_CEILING: f64 = 709.0;
62
+
63
+ /// Biased exponent field of `bits` (bits 52 to 62), as a signed integer.
64
+ fn exponent_field(bits: u64) -> i32 {
65
+ let [.., low, high] = bits.to_le_bytes();
66
+ i32::from((u16::from(high & 0x7F) << 4) | u16::from(low >> 4))
67
+ }
68
+
69
+ /// `2^power` for `-1022 <= power <= 1023`, the only powers the callers form.
70
+ fn power_of_two(power: i32) -> f64 {
71
+ debug_assert!(
72
+ (1 - EXPONENT_BIAS..=EXPONENT_BIAS).contains(&power),
73
+ "callers form only normal powers of two"
74
+ );
75
+ f64::from_bits(u64::from((power + EXPONENT_BIAS).cast_unsigned()) << MANTISSA_BITS)
76
+ }
77
+
78
+ /// `(exponent, mantissa)` with `x = mantissa * 2^exponent` and `mantissa` in
79
+ /// `[1, 2)`, for a finite positive `x`, subnormals included.
80
+ fn decompose(x: f64) -> (i32, f64) {
81
+ let (scaled, lift) = if x < f64::MIN_POSITIVE {
82
+ (x * TWO_54, LIFT)
83
+ } else {
84
+ (x, 0)
85
+ };
86
+ let bits = scaled.to_bits();
87
+ let mantissa = f64::from_bits((bits & MANTISSA_MASK) | ONE_BITS);
88
+ // The field is at most 2047 and `lift` 54: integer exponent arithmetic in
89
+ // this module stays within a few thousand of zero.
90
+ (exponent_field(bits) - EXPONENT_BIAS - lift, mantissa)
91
+ }
92
+
93
+ /// Square root of a finite non-negative `x`; zero for anything else.
94
+ pub fn sqrt(x: f64) -> f64 {
95
+ if x.is_nan() || x <= 0.0 || x.is_infinite() {
96
+ return 0.0;
97
+ }
98
+ let (mut exponent, mut mantissa) = decompose(x);
99
+ if exponent % 2 != 0 {
100
+ mantissa *= 2.0;
101
+ exponent -= 1;
102
+ }
103
+ let mut root = 0.5 + 0.5 * mantissa;
104
+ let mut step = 0;
105
+ while step < NEWTON_STEPS {
106
+ root = 0.5 * (root + mantissa / root);
107
+ step += 1;
108
+ }
109
+ root * power_of_two(exponent / 2)
110
+ }
111
+
112
+ /// `e^x`, saturating to zero below [`EXP_FLOOR`] and to infinity above
113
+ /// [`EXP_CEILING`].
114
+ pub fn exp(x: f64) -> f64 {
115
+ if x.is_nan() {
116
+ return x;
117
+ }
118
+ if x < EXP_FLOOR {
119
+ return 0.0;
120
+ }
121
+ if x > EXP_CEILING {
122
+ return f64::INFINITY;
123
+ }
124
+ let turns = x / LN_2;
125
+ let nearest = if turns < 0.0 {
126
+ turns - 0.5
127
+ } else {
128
+ turns + 0.5
129
+ };
130
+ #[allow(
131
+ clippy::cast_possible_truncation,
132
+ reason = "|nearest| <= 1024 after the range checks"
133
+ )]
134
+ let power = nearest as i32;
135
+ // Two-part ln(2): the high part times `power` is exact, so the reduced
136
+ // argument keeps full precision across the whole domain.
137
+ let rest = (x - f64::from(power) * LN_2_HIGH) - f64::from(power) * LN_2_LOW;
138
+ let mut sum = 1.0;
139
+ let mut degree = EXP_DEGREE;
140
+ while degree > 0 {
141
+ sum = 1.0 + sum * rest / f64::from(degree);
142
+ degree -= 1;
143
+ }
144
+ // Split the scale so that 2^1024 is never formed for results near the top.
145
+ let half = power / 2;
146
+ sum * power_of_two(half) * power_of_two(power - half)
147
+ }
148
+
149
+ /// Natural logarithm of a positive finite `x`; negative infinity for zero or
150
+ /// negative input.
151
+ pub fn ln(x: f64) -> f64 {
152
+ if x.is_nan() || x.is_infinite() {
153
+ return x;
154
+ }
155
+ if x <= 0.0 {
156
+ return f64::NEG_INFINITY;
157
+ }
158
+ let (power, mut mantissa) = decompose(x);
159
+ let mut exponent = f64::from(power);
160
+ if mantissa > core::f64::consts::SQRT_2 {
161
+ mantissa *= 0.5;
162
+ exponent += 1.0;
163
+ }
164
+ let t = (mantissa - 1.0) / (mantissa + 1.0);
165
+ let square = t * t;
166
+ let mut series = 0.0;
167
+ let mut term = LN_TERMS;
168
+ while term > 0 {
169
+ term -= 1;
170
+ series = 1.0 / f64::from(2 * term + 1) + series * square;
171
+ }
172
+ exponent * LN_2 + 2.0 * series * t
173
+ }
174
+
175
+ /// `erf(x)` for `0 <= x < SERIES_LIMIT`, from the all-positive series
176
+ /// `2/sqrt(pi) * e^(-x^2) * sum 2^n x^(2n+1) / (2n+1)!!`.
177
+ fn erf_series(x: f64) -> f64 {
178
+ let double_square = 2.0 * x * x;
179
+ let mut term = x;
180
+ let mut sum = x;
181
+ let mut index = 0;
182
+ while index < SERIES_TERMS {
183
+ term = term * double_square / f64::from(2 * index + 3);
184
+ sum += term;
185
+ index += 1;
186
+ }
187
+ FRAC_2_SQRT_PI * exp(-x * x) * sum
188
+ }
189
+
190
+ /// Denominator `f` of `erfc(x) = e^(-x^2) / (sqrt(pi) * f)` for
191
+ /// `x >= SERIES_LIMIT`: `f = x + (1/2)/(x + (2/2)/(x + (3/2)/(x + ...)))`.
192
+ fn erfc_fraction(x: f64) -> f64 {
193
+ let mut value = x;
194
+ let mut level = FRACTION_LEVELS;
195
+ while level > 0 {
196
+ value = x + (f64::from(level) * 0.5) / value;
197
+ level -= 1;
198
+ }
199
+ value
200
+ }
201
+
202
+ /// `-log10(Q(z))`, where `Q` is the upper tail of the standard normal
203
+ /// distribution. Evaluated in the log domain, so it stays finite and accurate
204
+ /// long after `Q(z)` itself would underflow. Never negative.
205
+ pub fn normal_phi(z: f64) -> f64 {
206
+ let late = z >= 0.0;
207
+ let x = if late { z } else { -z } * FRAC_1_SQRT_2;
208
+ let ln_tail = if x < SERIES_LIMIT {
209
+ let erf = erf_series(x);
210
+ ln(if late {
211
+ 0.5 * (1.0 - erf)
212
+ } else {
213
+ 0.5 * (1.0 + erf)
214
+ })
215
+ } else {
216
+ let upper = -x * x - ln(erfc_fraction(x)) - LN_2_SQRT_PI;
217
+ if late { upper } else { ln(1.0 - exp(upper)) }
218
+ };
219
+ let phi = -ln_tail / LN_10;
220
+ if phi > 0.0 { phi } else { 0.0 }
221
+ }
222
+
223
+ /// `-log10(e^(-ratio))` for the exponential tail: `ratio / ln(10)`.
224
+ pub fn exponential_phi(ratio: f64) -> f64 {
225
+ if ratio > 0.0 { ratio / LN_10 } else { 0.0 }
226
+ }
227
+
228
+ #[cfg(test)]
229
+ mod tests;