scirs2-special 0.4.2

Special functions module for SciRS2 (scirs2-special)
Documentation
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
//! Legendre elliptic integrals via Carlson symmetric forms
//!
//! This module provides high-accuracy implementations of the classical Legendre
//! elliptic integrals by expressing them in terms of Carlson symmetric forms
//! (RF, RD, RJ). This approach provides better numerical stability and
//! uniform accuracy across the entire parameter range.
//!
//! ## Complete Elliptic Integrals
//!
//! - `ellipk_carlson(m)`: K(m) = RF(0, 1-m, 1)
//! - `ellipe_carlson(m)`: E(m) = RF(0, 1-m, 1) - (m/3) RD(0, 1-m, 1)
//! - `ellippi_carlson(n, m)`: Pi(n, m) via RF and RJ
//!
//! ## Incomplete Elliptic Integrals
//!
//! - `ellipf_carlson(phi, m)`: F(phi, m) via RF
//! - `ellipe_inc_carlson(phi, m)`: E(phi, m) via RF and RD
//! - `ellippi_inc_carlson(n, phi, m)`: Pi(n, phi, m) via RF and RJ
//!
//! ## References
//!
//! - Carlson, B. C. (1995). "Numerical computation of real or complex elliptic integrals."
//!   *Numerical Algorithms*, 10(1), 13--26.
//! - DLMF Chapter 19: Elliptic Integrals.

use crate::carlson::{elliprd, elliprf, elliprj};
use crate::error::{SpecialError, SpecialResult};

/// Complete elliptic integral of the first kind K(m) via Carlson RF.
///
/// K(m) = RF(0, 1-m, 1)
///
/// # Arguments
/// * `m` - Parameter (0 <= m < 1)
///
/// # Returns
/// Value of K(m)
///
/// # Examples
/// ```
/// use scirs2_special::legendre_elliptic::ellipk_carlson;
/// let k = ellipk_carlson(0.0).expect("failed");
/// assert!((k - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
/// ```
pub fn ellipk_carlson(m: f64) -> SpecialResult<f64> {
    if !(0.0..1.0).contains(&m) {
        return Err(SpecialError::DomainError(format!(
            "m must be in [0, 1) for K(m), got {m}"
        )));
    }

    elliprf(0.0, 1.0 - m, 1.0)
}

/// Complete elliptic integral of the second kind E(m) via Carlson RF and RD.
///
/// E(m) = RF(0, 1-m, 1) - (m/3) * RD(0, 1-m, 1)
///
/// # Arguments
/// * `m` - Parameter (0 <= m <= 1)
///
/// # Returns
/// Value of E(m)
///
/// # Examples
/// ```
/// use scirs2_special::legendre_elliptic::ellipe_carlson;
/// let e = ellipe_carlson(0.0).expect("failed");
/// assert!((e - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
/// ```
pub fn ellipe_carlson(m: f64) -> SpecialResult<f64> {
    if !(0.0..=1.0).contains(&m) {
        return Err(SpecialError::DomainError(format!(
            "m must be in [0, 1] for E(m), got {m}"
        )));
    }

    if (m - 1.0).abs() < 1e-15 {
        return Ok(1.0);
    }

    let rf_val = elliprf(0.0, 1.0 - m, 1.0)?;
    let rd_val = elliprd(0.0, 1.0 - m, 1.0)?;
    Ok(rf_val - (m / 3.0) * rd_val)
}

/// Complete elliptic integral of the third kind Pi(n, m) via Carlson RF and RJ.
///
/// Pi(n, m) = RF(0, 1-m, 1) + (n/3) * RJ(0, 1-m, 1, 1-n)
///
/// # Arguments
/// * `n` - Characteristic (n < 1)
/// * `m` - Parameter (0 <= m < 1)
///
/// # Returns
/// Value of Pi(n, m)
///
/// # Examples
/// ```
/// use scirs2_special::legendre_elliptic::ellippi_carlson;
/// // Pi(0, m) = K(m)
/// let pi_val = ellippi_carlson(0.0, 0.5).expect("failed");
/// let k_val = scirs2_special::legendre_elliptic::ellipk_carlson(0.5).expect("failed");
/// assert!((pi_val - k_val).abs() < 1e-10);
/// ```
pub fn ellippi_carlson(n: f64, m: f64) -> SpecialResult<f64> {
    if !(0.0..1.0).contains(&m) {
        return Err(SpecialError::DomainError(format!(
            "m must be in [0, 1) for Pi(n, m), got {m}"
        )));
    }

    if (1.0 - n).abs() < 1e-15 {
        return Err(SpecialError::DomainError(
            "n = 1 gives a singular integral".to_string(),
        ));
    }

    let rf_val = elliprf(0.0, 1.0 - m, 1.0)?;

    if n.abs() < 1e-15 {
        return Ok(rf_val);
    }

    let rj_val = elliprj(0.0, 1.0 - m, 1.0, 1.0 - n)?;
    Ok(rf_val + (n / 3.0) * rj_val)
}

/// Incomplete elliptic integral of the first kind F(phi, m) via Carlson RF.
///
/// F(phi, m) = sin(phi) * RF(cos^2(phi), 1 - m*sin^2(phi), 1)
///
/// # Arguments
/// * `phi` - Amplitude angle in radians
/// * `m` - Parameter (0 <= m <= 1)
///
/// # Returns
/// Value of F(phi, m)
///
/// # Examples
/// ```
/// use scirs2_special::legendre_elliptic::ellipf_carlson;
/// // F(0, m) = 0
/// let f = ellipf_carlson(0.0, 0.5).expect("failed");
/// assert!(f.abs() < 1e-14);
/// ```
pub fn ellipf_carlson(phi: f64, m: f64) -> SpecialResult<f64> {
    if !(0.0..=1.0).contains(&m) {
        return Err(SpecialError::DomainError(format!(
            "m must be in [0, 1] for F(phi, m), got {m}"
        )));
    }

    if phi.abs() < 1e-300 {
        return Ok(0.0);
    }

    // Handle range reduction for |phi| > pi/2
    let sign = if phi < 0.0 { -1.0 } else { 1.0 };
    let phi = phi.abs();
    let half_pi = std::f64::consts::FRAC_PI_2;

    if phi <= half_pi {
        let sin_phi = phi.sin();
        let cos_phi = phi.cos();
        let sin2 = sin_phi * sin_phi;
        let cos2 = cos_phi * cos_phi;

        let rf_val = elliprf(cos2, 1.0 - m * sin2, 1.0)?;
        return Ok(sign * sin_phi * rf_val);
    }

    // For phi > pi/2, use the identity:
    // F(phi, m) = 2*n*K(m) + F(phi - n*pi, m)  where n = floor(phi/(pi/2) + 1/2) * ...
    // More precisely: F(phi + pi, m) = F(phi, m) + 2*K(m)
    let n_periods = (phi / std::f64::consts::PI).floor() as i64;
    let phi_rem = phi - (n_periods as f64) * std::f64::consts::PI;

    let mut result = 0.0;
    if n_periods > 0 && m < 1.0 {
        let k = ellipk_carlson(m)?;
        result += 2.0 * (n_periods as f64) * k;
    }

    if phi_rem > half_pi {
        // F(pi - x, m) = 2*K(m) - F(x, m)
        let x = std::f64::consts::PI - phi_rem;
        if m < 1.0 {
            let k = ellipk_carlson(m)?;
            result += 2.0 * k;
        }
        let sin_x = x.sin();
        let cos_x = x.cos();
        let sin2 = sin_x * sin_x;
        let cos2 = cos_x * cos_x;
        let rf_val = elliprf(cos2, 1.0 - m * sin2, 1.0)?;
        result -= sin_x * rf_val;
    } else {
        let sin_phi = phi_rem.sin();
        let cos_phi = phi_rem.cos();
        let sin2 = sin_phi * sin_phi;
        let cos2 = cos_phi * cos_phi;
        let rf_val = elliprf(cos2, 1.0 - m * sin2, 1.0)?;
        result += sin_phi * rf_val;
    }

    Ok(sign * result)
}

/// Incomplete elliptic integral of the second kind E(phi, m) via Carlson RF and RD.
///
/// E(phi, m) = sin(phi) * RF(cos^2, 1 - m*sin^2, 1)
///             - (m/3) * sin^3(phi) * RD(cos^2, 1 - m*sin^2, 1)
///
/// # Arguments
/// * `phi` - Amplitude angle in radians
/// * `m` - Parameter (0 <= m <= 1)
///
/// # Returns
/// Value of E(phi, m)
///
/// # Examples
/// ```
/// use scirs2_special::legendre_elliptic::ellipe_inc_carlson;
/// // E(0, m) = 0
/// let e = ellipe_inc_carlson(0.0, 0.5).expect("failed");
/// assert!(e.abs() < 1e-14);
/// ```
pub fn ellipe_inc_carlson(phi: f64, m: f64) -> SpecialResult<f64> {
    if !(0.0..=1.0).contains(&m) {
        return Err(SpecialError::DomainError(format!(
            "m must be in [0, 1] for E(phi, m), got {m}"
        )));
    }

    if phi.abs() < 1e-300 {
        return Ok(0.0);
    }

    let sign = if phi < 0.0 { -1.0 } else { 1.0 };
    let phi = phi.abs();
    let half_pi = std::f64::consts::FRAC_PI_2;

    if phi <= half_pi {
        let sin_phi = phi.sin();
        let cos_phi = phi.cos();
        let sin2 = sin_phi * sin_phi;
        let cos2 = cos_phi * cos_phi;
        let k2 = 1.0 - m * sin2;

        let rf_val = elliprf(cos2, k2, 1.0)?;
        let rd_val = elliprd(cos2, k2, 1.0)?;

        let result = sin_phi * rf_val - (m / 3.0) * sin_phi * sin2 * rd_val;
        return Ok(sign * result);
    }

    // Range reduction for phi > pi/2
    let n_periods = (phi / std::f64::consts::PI).floor() as i64;
    let phi_rem = phi - (n_periods as f64) * std::f64::consts::PI;

    let mut result = 0.0;
    if n_periods > 0 {
        let e_complete = ellipe_carlson(m)?;
        result += 2.0 * (n_periods as f64) * e_complete;
    }

    if phi_rem > half_pi {
        let x = std::f64::consts::PI - phi_rem;
        let e_complete = ellipe_carlson(m)?;
        result += 2.0 * e_complete;

        let sin_x = x.sin();
        let cos_x = x.cos();
        let sin2 = sin_x * sin_x;
        let cos2 = cos_x * cos_x;
        let k2 = 1.0 - m * sin2;

        let rf_val = elliprf(cos2, k2, 1.0)?;
        let rd_val = elliprd(cos2, k2, 1.0)?;
        result -= sin_x * rf_val - (m / 3.0) * sin_x * sin2 * rd_val;
    } else if phi_rem.abs() > 1e-300 {
        let sin_phi = phi_rem.sin();
        let cos_phi = phi_rem.cos();
        let sin2 = sin_phi * sin_phi;
        let cos2 = cos_phi * cos_phi;
        let k2 = 1.0 - m * sin2;

        let rf_val = elliprf(cos2, k2, 1.0)?;
        let rd_val = elliprd(cos2, k2, 1.0)?;
        result += sin_phi * rf_val - (m / 3.0) * sin_phi * sin2 * rd_val;
    }

    Ok(sign * result)
}

/// Incomplete elliptic integral of the third kind Pi(n, phi, m) via Carlson RF and RJ.
///
/// Pi(n, phi, m) = sin(phi) * RF(cos^2, 1 - m*sin^2, 1)
///                 + (n/3) * sin^3(phi) * RJ(cos^2, 1 - m*sin^2, 1, 1 - n*sin^2)
///
/// # Arguments
/// * `n` - Characteristic
/// * `phi` - Amplitude angle in radians
/// * `m` - Parameter (0 <= m <= 1)
///
/// # Returns
/// Value of Pi(n, phi, m)
///
/// # Examples
/// ```
/// use scirs2_special::legendre_elliptic::ellippi_inc_carlson;
/// // Pi(0, phi, m) = F(phi, m)
/// let pi_val = ellippi_inc_carlson(0.0, 0.5, 0.3).expect("failed");
/// let f_val = scirs2_special::legendre_elliptic::ellipf_carlson(0.5, 0.3).expect("failed");
/// assert!((pi_val - f_val).abs() < 1e-10);
/// ```
pub fn ellippi_inc_carlson(n: f64, phi: f64, m: f64) -> SpecialResult<f64> {
    if !(0.0..=1.0).contains(&m) {
        return Err(SpecialError::DomainError(format!(
            "m must be in [0, 1] for Pi(n, phi, m), got {m}"
        )));
    }

    if phi.abs() < 1e-300 {
        return Ok(0.0);
    }

    let sign = if phi < 0.0 { -1.0 } else { 1.0 };
    let phi = phi.abs();

    let sin_phi = phi.sin();
    let cos_phi = phi.cos();
    let sin2 = sin_phi * sin_phi;
    let cos2 = cos_phi * cos_phi;
    let k2 = 1.0 - m * sin2;
    let p2 = 1.0 - n * sin2;

    if p2.abs() < 1e-15 {
        return Err(SpecialError::DomainError(
            "Pi is singular when 1 - n*sin^2(phi) = 0".to_string(),
        ));
    }

    let rf_val = elliprf(cos2, k2, 1.0)?;
    let mut result = sin_phi * rf_val;

    if n.abs() > 1e-15 {
        let rj_val = elliprj(cos2, k2, 1.0, p2)?;
        result += (n / 3.0) * sin_phi * sin2 * rj_val;
    }

    Ok(sign * result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use std::f64::consts::{FRAC_PI_2, PI};

    #[test]
    fn test_ellipk_carlson_at_zero() {
        // K(0) = pi/2
        let k = ellipk_carlson(0.0).expect("K(0) failed");
        assert_relative_eq!(k, FRAC_PI_2, epsilon = 1e-12);
    }

    #[test]
    fn test_ellipk_carlson_at_half() {
        // K(0.5) ~ 1.854074677301372
        let k = ellipk_carlson(0.5).expect("K(0.5) failed");
        assert_relative_eq!(k, 1.854_074_677_301_37, epsilon = 1e-10);
    }

    #[test]
    fn test_ellipe_carlson_at_zero() {
        // E(0) = pi/2
        let e = ellipe_carlson(0.0).expect("E(0) failed");
        assert_relative_eq!(e, FRAC_PI_2, epsilon = 1e-12);
    }

    #[test]
    fn test_ellipe_carlson_at_one() {
        // E(1) = 1
        let e = ellipe_carlson(1.0).expect("E(1) failed");
        assert_relative_eq!(e, 1.0, epsilon = 1e-12);
    }

    #[test]
    fn test_ellipe_carlson_at_half() {
        // E(0.5) ~ 1.350643881047675
        let e = ellipe_carlson(0.5).expect("E(0.5) failed");
        assert_relative_eq!(e, 1.350_643_881_047_67, epsilon = 1e-8);
    }

    #[test]
    fn test_legendre_identity_k_e() {
        // Legendre's relation: K(m)*E(1-m) + E(m)*K(1-m) - K(m)*K(1-m) = pi/2
        let m = 0.3;
        let k_m = ellipk_carlson(m).expect("K(m) failed");
        let e_m = ellipe_carlson(m).expect("E(m) failed");
        let k_1m = ellipk_carlson(1.0 - m).expect("K(1-m) failed");
        let e_1m = ellipe_carlson(1.0 - m).expect("E(1-m) failed");

        let lhs = k_m * e_1m + e_m * k_1m - k_m * k_1m;
        assert_relative_eq!(lhs, FRAC_PI_2, epsilon = 1e-8);
    }

    #[test]
    fn test_ellippi_carlson_n_zero() {
        // Pi(0, m) = K(m)
        let pi_val = ellippi_carlson(0.0, 0.5).expect("Pi(0, 0.5) failed");
        let k_val = ellipk_carlson(0.5).expect("K(0.5) failed");
        assert_relative_eq!(pi_val, k_val, epsilon = 1e-10);
    }

    #[test]
    fn test_ellipf_carlson_at_zero() {
        // F(0, m) = 0
        let f = ellipf_carlson(0.0, 0.5).expect("F(0, m) failed");
        assert!(f.abs() < 1e-14);
    }

    #[test]
    fn test_ellipf_carlson_at_half_pi() {
        // F(pi/2, m) = K(m)
        let f = ellipf_carlson(FRAC_PI_2, 0.5).expect("F(pi/2, m) failed");
        let k = ellipk_carlson(0.5).expect("K(m) failed");
        assert_relative_eq!(f, k, epsilon = 1e-10);
    }

    #[test]
    fn test_ellipe_inc_carlson_at_zero() {
        // E(0, m) = 0
        let e = ellipe_inc_carlson(0.0, 0.5).expect("E(0, m) failed");
        assert!(e.abs() < 1e-14);
    }

    #[test]
    fn test_ellipe_inc_carlson_at_half_pi() {
        // E(pi/2, m) = E(m)
        let e_inc = ellipe_inc_carlson(FRAC_PI_2, 0.5).expect("E(pi/2, m) failed");
        let e_comp = ellipe_carlson(0.5).expect("E(m) failed");
        assert_relative_eq!(e_inc, e_comp, epsilon = 1e-8);
    }

    #[test]
    fn test_ellippi_inc_carlson_n_zero() {
        // Pi(0, phi, m) = F(phi, m)
        let phi = 0.7;
        let m = 0.3;
        let pi_val = ellippi_inc_carlson(0.0, phi, m).expect("Pi(0, phi, m) failed");
        let f_val = ellipf_carlson(phi, m).expect("F(phi, m) failed");
        assert_relative_eq!(pi_val, f_val, epsilon = 1e-10);
    }

    #[test]
    fn test_ellipf_carlson_odd() {
        // F(-phi, m) = -F(phi, m)
        let phi = 0.7;
        let m = 0.3;
        let f_pos = ellipf_carlson(phi, m).expect("failed");
        let f_neg = ellipf_carlson(-phi, m).expect("failed");
        assert_relative_eq!(f_pos, -f_neg, epsilon = 1e-10);
    }

    #[test]
    fn test_ellipk_carlson_increases() {
        // K(m) is monotonically increasing for m in [0, 1)
        let k1 = ellipk_carlson(0.1).expect("failed");
        let k2 = ellipk_carlson(0.5).expect("failed");
        let k3 = ellipk_carlson(0.9).expect("failed");
        assert!(k1 < k2, "K should increase: K(0.1)={k1} vs K(0.5)={k2}");
        assert!(k2 < k3, "K should increase: K(0.5)={k2} vs K(0.9)={k3}");
    }

    #[test]
    fn test_ellipk_carlson_domain() {
        assert!(ellipk_carlson(-0.1).is_err());
        assert!(ellipk_carlson(1.0).is_err());
    }

    #[test]
    fn test_ellipe_carlson_decreases() {
        // E(m) is monotonically decreasing for m in [0, 1]
        let e1 = ellipe_carlson(0.1).expect("failed");
        let e2 = ellipe_carlson(0.5).expect("failed");
        let e3 = ellipe_carlson(0.9).expect("failed");
        assert!(e1 > e2, "E should decrease");
        assert!(e2 > e3, "E should decrease");
    }
}