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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Forward-mode dual numbers carrying `N` first-order directional derivatives.
use array;
use Ordering;
use ;
use ;
use crateReal;
/// A value with `N` first-order derivatives: `re + Σᵢ eps[i]·εᵢ`.
///
/// # Comparisons and zero tests
///
/// `==`, `<` and the other comparisons look only at the value `re`, so a `Dual` orders like its
/// value. [`Zero::is_zero`] and [`One::is_one`] are strict: they also require every derivative
/// to be zero. Generic code uses them as shortcuts, where a value-only test would silently drop
/// derivatives: num-complex 0.4.6 returns early from `Complex::sqrt` and `cbrt` when a component
/// `is_zero()`, and returns `one()` from `powf`/`powc` when the exponent `is_zero()`. So for a
/// refractive index `m = n + 0i` with ∂/∂(Im m) seeded, `m.sqrt()` would lose that derivative.
/// ForwardDiff.jl made the same choice (v1.0, PR #481). `Float::is_nan` and `Float::is_finite`
/// also inspect the derivatives, so a NaN derivative is never silent; `is_infinite`,
/// `is_normal`, `is_subnormal`, `classify`, the sign tests and `integer_decode` describe the
/// value alone. A finite value with an infinite derivative is therefore neither NaN, infinite
/// nor finite.
///
/// In `num_complex::Complex<Dual<T, N>>`, strict zero tests change some values. Where a
/// component is zero in value but carries a derivative, num-complex skips its shortcut and takes
/// the general polar path, whose values are not always bitwise those of `Complex<T>` (the
/// derivatives on these paths are correct):
///
/// * `sqrt` on the imaginary axis differs by up to 2 ulps, and `cbrt` there always differs
/// (within 2 ulps in the tests);
/// * `sqrt(−4 + 0i)` gives `Re = 2·cos(π/2) ≈ 1.2e-16` instead of 0;
/// * `powf` with an exponent that is zero in value returns `1 − 0i` when arg z < 0, and NaN for
/// a NaN base, instead of `1 + 0i`;
/// * `powc` with such an exponent returns NaN at z = 0 and z = ∞ instead of 1;
/// * `ToPrimitive` returns `None` when the imaginary part is zero in value but has a
/// derivative.
///
/// And since `is_finite` sees derivatives, `Complex::exp` takes its corner case for `Re z = +∞`
/// when `Im z` has an infinite or NaN derivative, returning `(+∞, Im z)` instead of
/// `(∞·cos(Im z), ∞·sin(Im z))`.
///
/// # Arithmetic
///
/// The value of every operation is `T`'s operation on the values, so its rounding, special
/// values and signed zeros follow `T` bit for bit: `(a / b).re() == a.re() / b.re()`. With `a′`
/// and `b′` the derivatives (componentwise), `y` an `f64`, and `q` and `r` the computed quotient
/// and remainder, the derivatives are:
///
/// | Operation | Derivatives |
/// |---|---|
/// | `a + b`, `a - b`, `-a` | `a′ + b′`, `a′ − b′`, `−a′` |
/// | `a * b` | `a′·b + a·b′` |
/// | `a / b` | `(a′ − q·b′)·(1/b)`, or `(a′ − q·b′)/b` in the special cases below |
/// | `a % b` | `a′ − t·b′`, where `t` is the integer with `a = t·b + r` |
/// | `a + y`, `a - y` | `a′` |
/// | `a * y`, `a / y` | `a′·y`, `a′/y` |
///
/// Each formula is evaluated in `T`, so a derivative errs by a few units in the last place of
/// its largest term; cancellation between the terms is not compensated. An intermediate can
/// overflow although the derivative is finite, as with the same formula in `T`: for `a / b`
/// with `a = 1e300`, `b = 10` and `b′ = 1e10`, `q·b′` overflows and the derivative is −∞ where
/// the true value is −1e308.
///
/// `%` jumps where `a/b` is an integer; there the derivative is that of the branch that gave
/// the value (`t = a/b`, `r = ±0`). `t` is recovered from the exact remainder as
/// `round((a − r)/b)`, not as `trunc(a/b)`, which rounding can move to the next integer:
/// `1.0 / 0.1 == 10.0`, yet `1.0 % 0.1 == 1.0 − 9·0.1`. With `f64` the computed quotient is
/// within (2u + u²)·|t| of `t` (u = 2⁻⁵³), so the recovered `t` is exact for |t| < 2⁵¹ and
/// within (2u + u²)·|t| + ½ beyond; with `DoubleDouble` it is exact for |t| below about 2¹⁰⁰.
///
/// # Elementary functions
///
/// `Dual` implements `num_traits::Float`, `FloatConst` and [`Real`], so generic kernels and
/// `num_complex::Complex<Dual<T, N>>` carry derivatives, and `Dual<Dual<T, M>, N>` gives second
/// derivatives. The value of every method is `T`'s method on the value, bit for bit, including
/// special values and signed zeros. The exceptions are `sin` and `cos`, which take their values
/// and derivatives from one `T::sin_cos`, so that value-only and derivative calls of a kernel
/// agree. On Apple targets LLVM fuses an `f64` `sin` and `cos` of one argument into
/// `__sincos_stret`, whose sine can be an ulp off a lone `f64::sin` (about 1 in 13,000
/// arguments, e.g. 0.768039326588954 and −0.3820992815488752). The value is then the one every
/// `f64` code computing both functions of the argument gets, such as `Complex::exp`. `f64` code
/// computing only `sin x` gets the lone sine instead, which `Dual::sin` (which also needs `cos x`)
/// may then miss by an ulp. On glibc the fused and separate values agree. Constants (`FloatConst`,
/// `Real::from_f64`, `nan()`, `epsilon()`, …) have zero derivatives. With `x′` and `y′` the
/// derivatives of `self` and of the second argument:
///
/// | Methods | Derivatives |
/// |---|---|
/// | `floor`, `ceil`, `round`, `trunc`, `signum` | 0, also at the jumps |
/// | `fract` | `x′` |
/// | `abs`, `copysign` | `−x′` where the sign changes (for `abs`, a set sign bit, −0 too), else `x′` |
/// | `max`, `min`, `clamp` | those of the operand whose value is returned (see below) |
/// | `abs_sub` | `x′ − y′`, or 0 where `x <= y` |
/// | `mul_add(a, b)` | `x′·a + x·a′ + b′` |
/// | `recip` | `−(x′·r)·r` with `r = 1/x` |
/// | `powi(n)` | `n·xⁿ⁻¹·x′` (0 for `n = 0`) |
/// | `powf(y)` | `y·xʸ⁻¹·x′ + xʸ·ln x·y′`, the second term only if some `y′` is nonzero |
/// | `sqrt`, `cbrt` | `x′/(2√x)`, `x′/(3·∛x²)` |
/// | `exp`, `exp2`, `exp_m1` | `eˣ·x′`, `2ˣ·ln 2·x′`, `eˣ·x′` |
/// | `ln`, `log2`, `log10`, `ln_1p` | `x′/x`, `log₂e·x′/x`, `log₁₀e·x′/x`, `x′/(1 + x)` |
/// | `log(b)` | `(1/ln b)·x′/x − (log_b x/ln b)·b′/b` |
/// | `hypot(y)` | `x′·x/h + y′·y/h` |
/// | `sin`, `cos`, `tan` | `cos x·x′`, `−sin x·x′`, `(1 + tan²x)·x′` |
/// | `asin`, `acos`, `atan` | `±x′/√((1 − x)(1 + x))`, `x′/(1 + x²)` |
/// | `atan2(x)` (`self` is y) | `(x·y′ − y·x′)/(x² + y²)` |
/// | `sinh`, `cosh`, `tanh` | `cosh x·x′`, `sinh x·x′`, `x′/cosh²x` |
/// | `asinh`, `acosh`, `atanh` | `x′/√(x² + 1)`, `x′/√((x − 1)(x + 1))`, `x′/((1 − x)(1 + x))` |
/// | `to_degrees`, `to_radians` | `x′` times `T::one().to_degrees()` or `.to_radians()` |
///
/// Each f′(x) is evaluated in `T` from a form that neither cancels nor needlessly over- or
/// underflows:
///
/// * `asin`, `acos` and `atanh` use (1 − x)(1 + x); `exp_m1` uses (eˣ − 1) + 1 only where
/// eˣ − 1 ≥ −½, and eˣ below; `tanh` uses (1 − t)(1 + t) only where |t| ≤ ½, and 4e/(1 + e)²
/// with e = e^(−2|x|) beyond; `sinh` uses √(1 + sinh²x); and `sinh`, `asinh` and `acosh`
/// replace √(x² ± 1) by |x| beyond 2⁵⁴.
/// * `hypot` and `atan2` rescale arguments whose squares leave the normal range.
/// * `powf` uses y·(xʸ/x) while xʸ and xʸ/x are normal, and (y·xʸ)/x for |y| < 1 where xʸ/x
/// overflows. Otherwise it uses y·p·p with p = |x|^((y−1)/2), or |x|^(y/2)/√|x| where y − 1
/// is not exact, and p·ln x·p with p = x^(y/2), so that no subnormal or infinite power, or
/// rounded exponent, enters a normal result.
/// * `log` computes its two partials directly, not through `/`.
///
/// Accuracy was measured over each whole domain against high-precision derivatives
/// (`tests/dual_functions.rs`), down to the bottom of the normal range for `powf`, `hypot` and
/// `atan2`.
///
/// * The derivatives of `Dual<f64, N>` are within 5.1u (u = 2⁻⁵³) of the exact derivative at the
/// argument with Apple's libm, the worst being `tan`.
/// * The tests bound each one by the measured errors of the libm results it is computed from,
/// times their amplification, plus 1u per rounding, so the bounds hold for any libm.
/// * `Dual<DoubleDouble, N>` derivatives are within 2⁻⁹⁶ relative. For powers whose
/// `DoubleDouble` values are only that accurate, the bound is 2⁻⁹⁶ times max(1, |y ln x|) and,
/// for ∂/∂x, |(y − 1) ln x|.
/// * `DoubleDouble` has full precision only from 2⁻⁹⁶⁹ (`min_positive_value()`). Derivatives
/// computed from smaller arguments or intermediates lose precision, as such values do.
///
/// Special values, for a nonzero derivative `x′`:
///
/// * Outside a function's domain, where `T` returns NaN (`ln(−1)`, `asin(2)`, `acosh(½)`,
/// `sin(∞)`, `fract(∞)`, `log(−1, b)`), and for a NaN argument, the derivatives are NaN. Some
/// methods are exceptions:
/// * the piecewise-constant methods keep zero derivatives;
/// * `abs`, `copysign`, `max`, `min` and `clamp` keep those of the operand they return;
/// * `mul_add` and `abs_sub` follow the arithmetic rules (as `x·a + b` and `x − y`), where a
/// NaN value makes a derivative NaN only through a product.
/// * At a singular point of f′ on the edge of the domain the derivative is the one-sided limit:
/// +∞ for `sqrt`, `cbrt`, `ln`, `log2` and `log10` at either zero, for `ln_1p` at −1, for
/// `asin` and `atanh` at ±1 and for `acosh` at 1; −∞ for `acos` at ±1. `recip` and negative
/// powers at ±0 follow IEEE 754 (`recip` gives −∞).
/// * At ±∞ the derivatives are the limits: 0 for `sqrt`, `ln`, `atan`, `tanh`, `asinh`, …, and
/// ±∞ for `exp`, `sinh`, `cosh`, ….
/// * `powf`:
/// * x⁰ = 1 has derivative 0 in x everywhere (also at x = 0, ∞ or NaN);
/// * at x = 0, y·x^(y−1) is +∞, 1 or 0 for 0 < y < 1, y = 1 and y > 1;
/// * where x^(±∞) = 0, the derivative in x is the limit 0;
/// * the derivative in y, xʸ·ln x, is 0 where xʸ = 0 with x ≥ 0, and NaN for x < 0, where xʸ
/// is real only at integers y.
/// * `exp2` keeps a finite derivative where 2ˣ overflows but 2ˣ·ln 2 does not (x < 1024.53).
/// * `hypot` at the origin, where |z| has no derivative, has zero derivatives (a subgradient,
/// as for `sqrt(p * p + q * q)`). So `Complex::ln` at z = 0 gets derivative 0 in its real
/// part, ln|z|, silently, while `atan2`'s NaN flags the imaginary part.
/// * `atan2` jumps at the origin and has NaN derivatives there; with an infinite argument its
/// derivatives are 0.
/// * `log` at x = ±0 has the limit from the right in x, 1/(x·ln b) → ±∞ (as `ln`); at base ±0
/// it has derivative −sign(ln x)·∞ in the base (0 for x = 1, where the function is 0 for
/// every base); and at base 1 the IEEE 754 values of 1/(x·ln b).
/// * `max`, `min` and `clamp` take the derivatives of the operand whose value `T` returns: the
/// larger (or smaller), the one that is not NaN, and at a tie the one whose sign the result
/// has (`self` if both have it). `clamp` takes a bound's derivatives outside the interval and
/// `self`'s inside and at its ends; where `f64::clamp` would panic (a NaN bound, or
/// `min > max`) it returns NaN, as `DoubleDouble` does.
///
/// The chain rule multiplies `x′` by f′(x) evaluated in `T`. Where f′(x) itself overflows or
/// underflows, `x′·f′(x)` is therefore ±∞ or 0 even if it would be representable, as for an
/// intermediate of `/`. For example `atan` beyond |x| ≈ 1.3·10¹⁵⁴, where 1/(1 + x²)
/// underflows, has derivative 0 even for a huge `x′`.
///
/// In nested duals, the limits at singular points of `sqrt`, `ln`, `log2` and `log10` carry
/// inner derivatives (their second derivatives at 0 are −∞). The other special cases return
/// constants, and those have zero inner derivatives: the origin of `hypot` and `atan2`, the
/// limits of `powf`, and `log` at base 0.
///
/// # Special values and signed zeros
///
/// A derivative component that is exactly zero is a *strong zero*: it contributes zero even
/// when multiplied by an infinite or NaN factor. So a direction on which no operand depends
/// keeps derivative 0 whatever the values: `Dual::constant(2.0) * Dual::constant(f64::INFINITY)`
/// has zero derivatives, not NaN, and a derivative never depends on `N` or on the other
/// directions. In arithmetic with finite operands, a derivative is NaN only if the value is NaN
/// too (`0 / 0`, `x % 0`) or two terms of its formula overflow with opposite signs (`∞ − ∞`)
/// (for the elementary functions, see above). Otherwise
/// IEEE 754 rules apply: `x / 0` has derivative `x′/0 = ±∞`, `a / b` at `b = ±0` with `b′ ≠ 0`
/// is dominated by the `a·b′/b²` term, and a nonzero derivative times an infinite value is
/// infinite. An infinite or NaN derivative times a zero value is NaN, as in `T`.
///
/// The rule cannot tell a direction the operands do not depend on from one in which they are
/// stationary. For `p` seeded at 0, `p * p` rightly has derivative 0, so a square root of it
/// (`sqrt(p * p)`, or `(p * p).powf(0.25)`) gets derivative 0 at the singular point of the root,
/// where `|p|` and `|p|^½` have no derivative (the plain chain rule would give 0·∞ = NaN). Write
/// `abs` rather than the root of a square, if ±p′ is wanted there (`hypot` at the origin also
/// gives zero derivatives, by choice; see "Elementary functions").
///
/// The sign of a zero derivative is unspecified (it may be `+0` or `−0`). It carries no
/// information, and no operation lets it change a nonzero result.
///
/// # Speed
///
/// Operations are `#[inline]`, and the derivatives are fixed-length arrays that LLVM unrolls;
/// for `N = 4` and `N = 8` it packs them into SIMD lanes (two-lane NEON on aarch64), for
/// `N = 2` only in some code. `*`, `/`, `* f64`, `/ f64`, the chain rule and the formulas of
/// `recip`, `powf`, `hypot`, `atan2`, `log` and `mul_add` first check the values for the
/// special cases above (for `/`, three floating-point comparisons) and hand those to `#[cold]`
/// out-of-line code. These checks are branches, so unlike the same loop over `f64`, a loop over
/// many `Dual`s is not vectorised across elements. The correctly rounded value of `/` costs a
/// second division: `a/b` for the value and `1/b` for the derivatives.
///
/// An elementary function adds to `T`'s cost that of f′(x) and one multiplication per
/// derivative:
///
/// * almost nothing for `exp`, whose derivative is its value, or for `sin` and `cos`, which get
/// both from one `sin_cos`;
/// * a division for `sqrt`, `ln` and the inverse functions;
/// * a second function call for `cosh`, `tanh` (beyond |t| = ½) and `exp_m1` (below
/// eˣ − 1 = −½);
/// * `ln x` for `powf` with a varying exponent;
/// * for `DoubleDouble`, whose functions dominate, the second function is a second series.
///
/// # Examples
///
/// ```
/// use num_traits::Float;
/// use scatrs::scalar::Dual;
///
/// // d/dx (x sin x) = sin x + x cos x, at x = 2.
/// let x = Dual::<f64, 1>::new(2.0, [1.0]);
/// let y = x * x.sin();
/// assert_eq!(y.re(), 2.0 * 2f64.sin());
/// assert!((y.eps()[0] - (2f64.sin() + 2.0 * 2f64.cos())).abs() < 1e-15);
/// ```
// Special-value paths. Each checked operation calls one of the `*_special` functions below as
// `special(..).eps`. Measured on `Dual<f64, N>` (Apple M4, cycle counts):
// * out of line and `#[cold]`, a special path keeps the check a real, predicted branch; inline,
// LLVM turned small ones into selects that put the check on the critical path (a multiply
// chain with N = 1 took 2.2× the cycles, a division chain 1.9×);
// * returning the whole `Dual` keeps the merge in floating-point registers (a `[f64; 1]` is
// returned in an integer register), and taking `.eps` rather than returning early keeps the
// fast path's result out of the return slot (an early return cost ~14% throughput at N = 4);
// * operands go by value; by reference measured the same or slower;
// * branch-free strong zeros everywhere, instead of a check, cost ~25% throughput at N = 4.
/// The strong-zero product of a derivative component `e` and a factor `v`: `+0` whenever
/// `e.is_zero()` (`e` is `±0`; for a nested `Dual`, zero in every part), whatever `v` is,
/// including ±∞ and NaN; otherwise exactly `e * v`, so a nonzero `e` times ±∞ or NaN still gives
/// ±∞ or NaN.
/// The strong-zero quotient of a derivative component `e` by `v`: `+0` whenever `e.is_zero()`,
/// whatever `v` is, including ±0 and NaN; otherwise exactly `e / v`, so a nonzero `e` divided
/// by ±0 gives ±∞.
/// Value `f`, derivatives `x′·df` with strong zeros (`df` infinite or NaN, or `f` NaN), where
/// `df` is first replaced by NaN if `f` is NaN and by `fix(x, f, df)` otherwise.
/// `a * b` with strong zeros (a value is infinite or NaN, or the product overflowed).
/// `a * y` with strong zeros (`y` infinite or NaN).
/// `a / y` with strong zeros (`y` zero or NaN).
/// `a / b` with quotient `q`, when the fast path's `(a′ − q·b′)·(1/b)` could meet 0·∞ or a
/// reciprocal without full precision: `(a′ − q·b′)/b`, divided directly, with strong zeros.
assign_ops!;
/// Compares the values only.
/// Compares the values only.
/// Converts the value with `T`'s conversions, ignoring the derivatives.