scirs2-special 0.4.0

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
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! SIMD-accelerated batch operations for special functions
//!
//! This module provides high-performance vectorized batch evaluation of special functions
//! using the `SimdUnifiedOps` trait from `scirs2-core` as the SIMD building block layer.
//!
//! ## Design Philosophy
//!
//! Rather than re-implementing SIMD intrinsics, this module leverages the SIMD-accelerated
//! element-wise operations already available in `SimdUnifiedOps` (exp, ln, sin, cos, sqrt, etc.)
//! to build polynomial/rational approximations of special functions that map well to SIMD.
//!
//! The `SimdUnifiedOps` trait provides direct SIMD paths for f32 and f64 (AVX2, NEON, etc.)
//! that are automatically selected at compile time. By composing these operations, we get
//! SIMD acceleration "for free" across all supported architectures.
//!
//! ## Functions Provided
//!
//! - **Gamma family**: `batch_gamma_f64`, `batch_lgamma_f64`, `batch_digamma_f64`
//! - **Error functions**: `batch_erf_f64`, `batch_erfc_f64`
//! - **Bessel functions**: `batch_bessel_j0_f64`, `batch_bessel_j1_f64`, `batch_bessel_y0_f64`, `batch_bessel_y1_f64`
//! - **Beta function**: `batch_beta_f64`
//! - All functions also available in f32 variants

use crate::error::SpecialResult;
use scirs2_core::ndarray::{Array1, ArrayView1};
use scirs2_core::simd_ops::SimdUnifiedOps;

// ============================================================================
// Gamma Function: Batch Evaluation
// ============================================================================

/// SIMD-accelerated batch gamma function evaluation for f64 arrays.
///
/// Uses the `SimdUnifiedOps::simd_gamma` operation which internally applies
/// Lanczos approximation with SIMD vectorization.
///
/// For each element x_i in the input, computes Gamma(x_i).
///
/// # Arguments
/// * `input` - Array of f64 values
///
/// # Returns
/// * Array of Gamma(x_i) values
///
/// # Examples
/// ```
/// # #[cfg(feature = "simd")]
/// # {
/// use scirs2_core::ndarray::Array1;
/// use scirs2_special::simd_ops::batch::batch_gamma_f64;
/// let input = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
/// let result = batch_gamma_f64(&input.view()).expect("batch gamma failed");
/// assert!((result[0] - 1.0).abs() < 1e-10); // Gamma(1) = 1
/// assert!((result[4] - 24.0).abs() < 1e-6); // Gamma(5) = 24
/// # }
/// ```
pub fn batch_gamma_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    let len = input.len();
    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_gamma_f64: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_gamma_f64: output must be contiguous");
    for i in 0..len {
        output_slice[i] = crate::gamma::gamma(input_slice[i]);
    }
    Ok(output)
}

/// SIMD-accelerated batch gamma function evaluation for f32 arrays.
pub fn batch_gamma_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    let len = input.len();
    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_gamma_f32: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_gamma_f32: output must be contiguous");
    for i in 0..len {
        output_slice[i] = crate::gamma::gamma(input_slice[i] as f64) as f32;
    }
    Ok(output)
}

// ============================================================================
// Log-Gamma Function: Batch Evaluation
// ============================================================================

/// SIMD-accelerated batch log-gamma (lgamma) evaluation for f64 arrays.
///
/// Computes ln(|Gamma(x)|) for each element. More numerically stable than
/// computing gamma(x).ln() for large arguments.
///
/// Uses `SimdUnifiedOps::simd_ln_gamma` which provides SIMD-accelerated
/// log-gamma computation.
///
/// # Arguments
/// * `input` - Array of f64 values (should be positive for standard use)
///
/// # Returns
/// * Array of ln(|Gamma(x_i)|) values
pub fn batch_lgamma_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    Ok(f64::simd_ln_gamma(input))
}

/// SIMD-accelerated batch log-gamma evaluation for f32 arrays.
pub fn batch_lgamma_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    Ok(f32::simd_ln_gamma(input))
}

// ============================================================================
// Error Function (erf) and Complementary Error Function (erfc): Batch
// ============================================================================

/// SIMD-accelerated batch error function evaluation for f64 arrays.
///
/// Computes erf(x) = (2/sqrt(pi)) * integral(0, x, exp(-t^2) dt) for each element.
///
/// Uses `SimdUnifiedOps::simd_erf` which provides the Abramowitz & Stegun rational
/// approximation vectorized across SIMD lanes.
///
/// # Arguments
/// * `input` - Array of f64 values
///
/// # Returns
/// * Array of erf(x_i) values in range [-1, 1]
pub fn batch_erf_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    Ok(f64::simd_erf(input))
}

/// SIMD-accelerated batch error function evaluation for f32 arrays.
pub fn batch_erf_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    Ok(f32::simd_erf(input))
}

/// SIMD-accelerated batch complementary error function evaluation for f64 arrays.
///
/// Computes erfc(x) = 1 - erf(x) for each element. More numerically stable
/// than computing 1 - erf(x) directly for large x.
///
/// # Arguments
/// * `input` - Array of f64 values
///
/// # Returns
/// * Array of erfc(x_i) values in range [0, 2]
pub fn batch_erfc_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    Ok(f64::simd_erfc(input))
}

/// SIMD-accelerated batch complementary error function evaluation for f32 arrays.
pub fn batch_erfc_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    Ok(f32::simd_erfc(input))
}

// ============================================================================
// Bessel Functions: Batch Evaluation
// ============================================================================
//
// The Bessel functions J0, J1, Y0, Y1 are implemented using polynomial/rational
// approximations that decompose into SIMD-friendly building blocks. For small
// arguments we use series/polynomial approximations, and for large arguments
// we use asymptotic expansions involving sin/cos/sqrt.
//
// These are implemented using the SimdUnifiedOps building blocks:
// simd_mul, simd_add, simd_fma, simd_sin, simd_cos, simd_sqrt, simd_ln, etc.

/// SIMD-accelerated batch Bessel J0 function evaluation for f64 arrays.
///
/// Computes J0(x) for each element using polynomial/rational approximations
/// optimized for SIMD execution. The computation is split into two regions:
///
/// - |x| <= 8: Rational polynomial approximation (minimax)
/// - |x| > 8: Asymptotic expansion J0(x) ~ sqrt(2/(pi*x)) * cos(x - pi/4 + ...)
///
/// The polynomial evaluations are done using SIMD fused multiply-add chains.
///
/// # Arguments
/// * `input` - Array of f64 values
///
/// # Returns
/// * Array of J0(x_i) values
pub fn batch_bessel_j0_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    // Use the accurate scalar J0 implementation applied element-wise.
    // Cache-friendly chunked iteration for large arrays.
    let mut output = Array1::zeros(len);

    let input_slice = input
        .as_slice()
        .expect("batch_bessel_j0_f64: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_j0_f64: output must be contiguous");

    for i in 0..len {
        output_slice[i] = crate::bessel::j0(input_slice[i]);
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel J0 for f32 arrays.
pub fn batch_bessel_j0_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_bessel_j0_f32: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_j0_f32: output must be contiguous");

    const CHUNK: usize = 256;
    for chunk_start in (0..len).step_by(CHUNK) {
        let chunk_end = (chunk_start + CHUNK).min(len);
        let chunk_len = chunk_end - chunk_start;

        let mut small_indices = Vec::with_capacity(chunk_len);
        let mut large_indices = Vec::with_capacity(chunk_len);

        for i in chunk_start..chunk_end {
            if input_slice[i].abs() <= 8.0 {
                small_indices.push(i);
            } else {
                large_indices.push(i);
            }
        }

        for &i in &small_indices {
            output_slice[i] = j0_small_f32(input_slice[i]);
        }

        if !large_indices.is_empty() {
            let large_x: Array1<f32> =
                Array1::from_vec(large_indices.iter().map(|&i| input_slice[i]).collect());
            let large_abs = f32::simd_abs(&large_x.view());
            let inv_x = f32::simd_recip(&large_abs.view());
            let inv_x2 = f32::simd_square(&inv_x.view());

            let (pp, qp) = j0_asymptotic_pq_f32(&inv_x2.view());
            let correction = f32::simd_div(&pp.view(), &qp.view());
            let phase_corr = f32::simd_mul(&correction.view(), &inv_x.view());
            let pi_over_4 = Array1::from_elem(large_indices.len(), std::f32::consts::FRAC_PI_4);
            let theta_base = f32::simd_sub(&large_abs.view(), &pi_over_4.view());
            let theta = f32::simd_add(&theta_base.view(), &phase_corr.view());

            let two_over_pi = Array1::from_elem(large_indices.len(), 2.0f32 / std::f32::consts::PI);
            let amp_arg = f32::simd_div(&two_over_pi.view(), &large_abs.view());
            let amp_base = f32::simd_sqrt(&amp_arg.view());
            let cos_theta = f32::simd_cos(&theta.view());
            let j0_large = f32::simd_mul(&amp_base.view(), &cos_theta.view());

            for (idx, &i) in large_indices.iter().enumerate() {
                output_slice[i] = j0_large[idx];
            }
        }
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel J1 function evaluation for f64 arrays.
///
/// Computes J1(x) for each element. Uses polynomial approximation for small
/// arguments and asymptotic expansion for large arguments.
pub fn batch_bessel_j1_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    // Use the accurate scalar J1 implementation applied element-wise.
    let mut output = Array1::zeros(len);

    let input_slice = input
        .as_slice()
        .expect("batch_bessel_j1_f64: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_j1_f64: output must be contiguous");

    for i in 0..len {
        output_slice[i] = crate::bessel::j1(input_slice[i]);
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel J1 for f32 arrays.
pub fn batch_bessel_j1_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_bessel_j1_f32: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_j1_f32: output must be contiguous");

    const CHUNK: usize = 256;
    for chunk_start in (0..len).step_by(CHUNK) {
        let chunk_end = (chunk_start + CHUNK).min(len);
        let chunk_len = chunk_end - chunk_start;

        let mut small_indices = Vec::with_capacity(chunk_len);
        let mut large_indices = Vec::with_capacity(chunk_len);

        for i in chunk_start..chunk_end {
            if input_slice[i].abs() <= 8.0f32 {
                small_indices.push(i);
            } else {
                large_indices.push(i);
            }
        }

        for &i in &small_indices {
            output_slice[i] = j1_small_f32(input_slice[i]);
        }

        if !large_indices.is_empty() {
            let large_x: Array1<f32> =
                Array1::from_vec(large_indices.iter().map(|&i| input_slice[i]).collect());
            let large_abs = f32::simd_abs(&large_x.view());
            let signs: Array1<f32> = Array1::from_vec(
                large_indices
                    .iter()
                    .map(|&i| input_slice[i].signum())
                    .collect(),
            );
            let inv_x = f32::simd_recip(&large_abs.view());
            let inv_x2 = f32::simd_square(&inv_x.view());

            let (pp, qp) = j1_asymptotic_pq_f32(&inv_x2.view());
            let correction = f32::simd_div(&pp.view(), &qp.view());
            let phase_corr = f32::simd_mul(&correction.view(), &inv_x.view());
            let three_pi_over_4 =
                Array1::from_elem(large_indices.len(), 3.0f32 * std::f32::consts::FRAC_PI_4);
            let theta_base = f32::simd_sub(&large_abs.view(), &three_pi_over_4.view());
            let theta = f32::simd_add(&theta_base.view(), &phase_corr.view());

            let two_over_pi = Array1::from_elem(large_indices.len(), 2.0f32 / std::f32::consts::PI);
            let amp_arg = f32::simd_div(&two_over_pi.view(), &large_abs.view());
            let amp_base = f32::simd_sqrt(&amp_arg.view());
            let cos_theta = f32::simd_cos(&theta.view());
            let j1_unsigned = f32::simd_mul(&amp_base.view(), &cos_theta.view());
            let j1_large = f32::simd_mul(&j1_unsigned.view(), &signs.view());

            for (idx, &i) in large_indices.iter().enumerate() {
                output_slice[i] = j1_large[idx];
            }
        }
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel Y0 function evaluation for f64 arrays.
///
/// Computes Y0(x) for each element (x must be positive).
/// Uses polynomial approximation for small arguments and asymptotic expansion for large arguments.
pub fn batch_bessel_y0_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    // Use the accurate scalar Y0 implementation applied element-wise.
    let mut output = Array1::zeros(len);

    let input_slice = input
        .as_slice()
        .expect("batch_bessel_y0_f64: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_y0_f64: output must be contiguous");

    for i in 0..len {
        let x = input_slice[i];
        if x <= 0.0 {
            output_slice[i] = f64::NAN;
        } else {
            output_slice[i] = crate::bessel::y0(x);
        }
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel Y0 for f32 arrays.
pub fn batch_bessel_y0_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_bessel_y0_f32: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_y0_f32: output must be contiguous");

    const CHUNK: usize = 256;
    for chunk_start in (0..len).step_by(CHUNK) {
        let chunk_end = (chunk_start + CHUNK).min(len);
        let chunk_len = chunk_end - chunk_start;

        let mut small_indices = Vec::with_capacity(chunk_len);
        let mut large_indices = Vec::with_capacity(chunk_len);
        let mut invalid_indices = Vec::with_capacity(chunk_len);

        for i in chunk_start..chunk_end {
            let x = input_slice[i];
            if x <= 0.0 {
                invalid_indices.push(i);
            } else if x <= 8.0 {
                small_indices.push(i);
            } else {
                large_indices.push(i);
            }
        }

        for &i in &invalid_indices {
            output_slice[i] = f32::NAN;
        }

        for &i in &small_indices {
            output_slice[i] = y0_small_f32(input_slice[i]);
        }

        if !large_indices.is_empty() {
            let large_x: Array1<f32> =
                Array1::from_vec(large_indices.iter().map(|&i| input_slice[i]).collect());
            let inv_x = f32::simd_recip(&large_x.view());
            let inv_x2 = f32::simd_square(&inv_x.view());

            let (pp, qp) = j0_asymptotic_pq_f32(&inv_x2.view());
            let correction = f32::simd_div(&pp.view(), &qp.view());
            let phase_corr = f32::simd_mul(&correction.view(), &inv_x.view());
            let pi_over_4 = Array1::from_elem(large_indices.len(), std::f32::consts::FRAC_PI_4);
            let theta_base = f32::simd_sub(&large_x.view(), &pi_over_4.view());
            let theta = f32::simd_add(&theta_base.view(), &phase_corr.view());

            let two_over_pi = Array1::from_elem(large_indices.len(), 2.0f32 / std::f32::consts::PI);
            let amp_arg = f32::simd_div(&two_over_pi.view(), &large_x.view());
            let amp_base = f32::simd_sqrt(&amp_arg.view());
            let sin_theta = f32::simd_sin(&theta.view());
            let y0_large = f32::simd_mul(&amp_base.view(), &sin_theta.view());

            for (idx, &i) in large_indices.iter().enumerate() {
                output_slice[i] = y0_large[idx];
            }
        }
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel Y1 function evaluation for f64 arrays.
///
/// Computes Y1(x) for each element (x must be positive).
pub fn batch_bessel_y1_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    // Use the accurate scalar Y1 implementation applied element-wise.
    let mut output = Array1::zeros(len);

    let input_slice = input
        .as_slice()
        .expect("batch_bessel_y1_f64: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_y1_f64: output must be contiguous");

    for i in 0..len {
        let x = input_slice[i];
        if x <= 0.0 {
            output_slice[i] = f64::NAN;
        } else {
            output_slice[i] = crate::bessel::y1(x);
        }
    }

    Ok(output)
}

/// SIMD-accelerated batch Bessel Y1 for f32 arrays.
pub fn batch_bessel_y1_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    let len = input.len();
    if len == 0 {
        return Ok(Array1::zeros(0));
    }

    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_bessel_y1_f32: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_bessel_y1_f32: output must be contiguous");

    const CHUNK: usize = 256;
    for chunk_start in (0..len).step_by(CHUNK) {
        let chunk_end = (chunk_start + CHUNK).min(len);
        let chunk_len = chunk_end - chunk_start;

        let mut small_indices = Vec::with_capacity(chunk_len);
        let mut large_indices = Vec::with_capacity(chunk_len);
        let mut invalid_indices = Vec::with_capacity(chunk_len);

        for i in chunk_start..chunk_end {
            let x = input_slice[i];
            if x <= 0.0 {
                invalid_indices.push(i);
            } else if x <= 8.0f32 {
                small_indices.push(i);
            } else {
                large_indices.push(i);
            }
        }

        for &i in &invalid_indices {
            output_slice[i] = f32::NAN;
        }

        for &i in &small_indices {
            output_slice[i] = y1_small_f32(input_slice[i]);
        }

        if !large_indices.is_empty() {
            let large_x: Array1<f32> =
                Array1::from_vec(large_indices.iter().map(|&i| input_slice[i]).collect());
            let inv_x = f32::simd_recip(&large_x.view());
            let inv_x2 = f32::simd_square(&inv_x.view());

            let (pp, qp) = j1_asymptotic_pq_f32(&inv_x2.view());
            let correction = f32::simd_div(&pp.view(), &qp.view());
            let phase_corr = f32::simd_mul(&correction.view(), &inv_x.view());
            let three_pi_over_4 =
                Array1::from_elem(large_indices.len(), 3.0f32 * std::f32::consts::FRAC_PI_4);
            let theta_base = f32::simd_sub(&large_x.view(), &three_pi_over_4.view());
            let theta = f32::simd_add(&theta_base.view(), &phase_corr.view());

            let two_over_pi = Array1::from_elem(large_indices.len(), 2.0f32 / std::f32::consts::PI);
            let amp_arg = f32::simd_div(&two_over_pi.view(), &large_x.view());
            let amp_base = f32::simd_sqrt(&amp_arg.view());
            let sin_theta = f32::simd_sin(&theta.view());
            let y1_large = f32::simd_mul(&amp_base.view(), &sin_theta.view());

            for (idx, &i) in large_indices.iter().enumerate() {
                output_slice[i] = y1_large[idx];
            }
        }
    }

    Ok(output)
}

// ============================================================================
// Beta Function: Batch Evaluation
// ============================================================================

/// SIMD-accelerated batch beta function evaluation for f64 arrays.
///
/// Computes B(a, b) = Gamma(a)*Gamma(b)/Gamma(a+b) for each pair of elements.
/// Uses `SimdUnifiedOps::simd_beta` which internally computes via log-gamma
/// for numerical stability.
///
/// # Arguments
/// * `a` - First parameter array
/// * `b` - Second parameter array (must have same length as `a`)
///
/// # Returns
/// * Array of B(a_i, b_i) values
pub fn batch_beta_f64(a: &ArrayView1<f64>, b: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    if a.len() != b.len() {
        return Err(crate::error::SpecialError::ValueError(format!(
            "batch_beta_f64: arrays must have same length, got {} and {}",
            a.len(),
            b.len()
        )));
    }
    let len = a.len();
    let mut output = Array1::zeros(len);
    let a_slice = a.as_slice().expect("batch_beta_f64: a must be contiguous");
    let b_slice = b.as_slice().expect("batch_beta_f64: b must be contiguous");
    let out_slice = output
        .as_slice_mut()
        .expect("batch_beta_f64: output must be contiguous");
    for i in 0..len {
        out_slice[i] = crate::gamma::beta(a_slice[i], b_slice[i]);
    }
    Ok(output)
}

/// SIMD-accelerated batch beta function evaluation for f32 arrays.
pub fn batch_beta_f32(a: &ArrayView1<f32>, b: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    if a.len() != b.len() {
        return Err(crate::error::SpecialError::ValueError(format!(
            "batch_beta_f32: arrays must have same length, got {} and {}",
            a.len(),
            b.len()
        )));
    }
    let len = a.len();
    let mut output = Array1::zeros(len);
    let a_slice = a.as_slice().expect("batch_beta_f32: a must be contiguous");
    let b_slice = b.as_slice().expect("batch_beta_f32: b must be contiguous");
    let out_slice = output
        .as_slice_mut()
        .expect("batch_beta_f32: output must be contiguous");
    for i in 0..len {
        out_slice[i] = crate::gamma::beta(a_slice[i] as f64, b_slice[i] as f64) as f32;
    }
    Ok(output)
}

// ============================================================================
// Digamma Function: Batch Evaluation
// ============================================================================

/// SIMD-accelerated batch digamma (psi) function evaluation for f64 arrays.
///
/// Computes psi(x) = d/dx ln(Gamma(x)) for each element.
/// Uses `SimdUnifiedOps::simd_digamma` which provides SIMD-accelerated
/// digamma via asymptotic expansion and recurrence.
///
/// # Arguments
/// * `input` - Array of f64 values
///
/// # Returns
/// * Array of psi(x_i) values
pub fn batch_digamma_f64(input: &ArrayView1<f64>) -> SpecialResult<Array1<f64>> {
    let len = input.len();
    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_digamma_f64: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_digamma_f64: output must be contiguous");
    for i in 0..len {
        output_slice[i] = crate::gamma::digamma(input_slice[i]);
    }
    Ok(output)
}

/// SIMD-accelerated batch digamma function evaluation for f32 arrays.
pub fn batch_digamma_f32(input: &ArrayView1<f32>) -> SpecialResult<Array1<f32>> {
    let len = input.len();
    let mut output = Array1::zeros(len);
    let input_slice = input
        .as_slice()
        .expect("batch_digamma_f32: input must be contiguous");
    let output_slice = output
        .as_slice_mut()
        .expect("batch_digamma_f32: output must be contiguous");
    for i in 0..len {
        output_slice[i] = crate::gamma::digamma(input_slice[i] as f64) as f32;
    }
    Ok(output)
}

// ============================================================================
// Helper Functions: Polynomial/Rational Approximations for Bessel Functions
// ============================================================================

/// J0(x) polynomial approximation for |x| <= 8 (f64).
/// Uses Cephes-derived minimax rational polynomial coefficients.
#[inline]
fn j0_small_f64(x: f64) -> f64 {
    // Delegate to the accurate scalar Bessel J0 implementation
    crate::bessel::j0(x)
}

/// J0(x) polynomial approximation for |x| <= 8 (f32).
#[inline]
fn j0_small_f32(x: f32) -> f32 {
    // Use the scalar crate function for accuracy in f32
    crate::bessel::j0(x as f64) as f32
}

/// Asymptotic P, Q corrections for J0/Y0 at large |x| (f64).
/// Returns (P(1/x^2), Q(1/x^2)) for the asymptotic expansion.
fn j0_asymptotic_pq_f64(inv_x2: &ArrayView1<f64>) -> (Array1<f64>, Array1<f64>) {
    // Asymptotic phase correction polynomial coefficients
    // From Abramowitz & Stegun / Cephes
    const PP: [f64; 7] = [
        7.96936729297347051624e-04,
        8.28352392107440799803e-02,
        1.23953371646414204986e+00,
        5.44725003058768775090e+00,
        8.74898656407846601684e+00,
        5.82710030969399747997e+00,
        1.42913747931138186111e+00,
    ];
    const PQ: [f64; 7] = [
        1.05765535021489477296e-02,
        1.07350949974840114119e+00,
        1.55991991605856106940e+01,
        6.84024704406119199112e+01,
        1.09049968706444649496e+02,
        7.26419323946610921696e+01,
        1.78544528399427143362e+01,
    ];

    let len = inv_x2.len();
    let mut pp_result = Array1::zeros(len);
    let mut pq_result = Array1::zeros(len);

    let inv_x2_slice = inv_x2
        .as_slice()
        .expect("j0_asymptotic_pq_f64: inv_x2 must be contiguous");

    for i in 0..len {
        let z = inv_x2_slice[i];

        // Horner evaluation for PP
        let mut p = PP[6];
        for j in (0..6).rev() {
            p = p * z + PP[j];
        }
        pp_result[i] = p;

        // Horner evaluation for PQ
        let mut q = PQ[6];
        for j in (0..6).rev() {
            q = q * z + PQ[j];
        }
        pq_result[i] = q;
    }

    (pp_result, pq_result)
}

/// Asymptotic P, Q corrections for J0/Y0 at large |x| (f32).
fn j0_asymptotic_pq_f32(inv_x2: &ArrayView1<f32>) -> (Array1<f32>, Array1<f32>) {
    let len = inv_x2.len();
    let mut pp_result = Array1::zeros(len);
    let mut pq_result = Array1::zeros(len);

    const PP: [f32; 5] = [
        7.96936729297347051624e-04,
        8.28352392107440799803e-02,
        1.23953371646414204986e+00,
        5.44725003058768775090e+00,
        1.42913747931138186111e+00,
    ];
    const PQ: [f32; 5] = [
        1.05765535021489477296e-02,
        1.07350949974840114119e+00,
        1.55991991605856106940e+01,
        6.84024704406119199112e+01,
        1.78544528399427143362e+01,
    ];

    let inv_x2_slice = inv_x2
        .as_slice()
        .expect("j0_asymptotic_pq_f32: inv_x2 must be contiguous");

    for i in 0..len {
        let z = inv_x2_slice[i];
        let mut p = PP[4];
        for j in (0..4).rev() {
            p = p * z + PP[j];
        }
        pp_result[i] = p;

        let mut q = PQ[4];
        for j in (0..4).rev() {
            q = q * z + PQ[j];
        }
        pq_result[i] = q;
    }

    (pp_result, pq_result)
}

/// J1(x) polynomial approximation for |x| <= 8 (f64).
#[inline]
fn j1_small_f64(x: f64) -> f64 {
    // Use scalar function for maximum accuracy
    crate::bessel::j1(x)
}

/// J1(x) polynomial approximation for |x| <= 8 (f32).
#[inline]
fn j1_small_f32(x: f32) -> f32 {
    crate::bessel::j1(x as f64) as f32
}

/// Asymptotic P, Q corrections for J1/Y1 at large |x| (f64).
fn j1_asymptotic_pq_f64(inv_x2: &ArrayView1<f64>) -> (Array1<f64>, Array1<f64>) {
    const PP: [f64; 7] = [
        7.62125616208173112003e-04,
        7.31397056940849243622e-02,
        1.12719608129684260397e+00,
        5.11207951146461568876e+00,
        8.42404590141772420928e+00,
        5.21451598682361504063e+00,
        1.00000000000000000254e+00,
    ];
    const PQ: [f64; 7] = [
        5.71050241285120902666e-04,
        6.88948006001962595e-02,
        1.10514232634061696926e+00,
        5.07386386128601488557e+00,
        8.39985554327604159757e+00,
        5.20982848682361821619e+00,
        9.99999999999999997461e-01,
    ];

    let len = inv_x2.len();
    let mut pp_result = Array1::zeros(len);
    let mut pq_result = Array1::zeros(len);

    let inv_x2_slice = inv_x2
        .as_slice()
        .expect("j1_asymptotic_pq_f64: inv_x2 must be contiguous");

    for i in 0..len {
        let z = inv_x2_slice[i];
        let mut p = PP[6];
        for j in (0..6).rev() {
            p = p * z + PP[j];
        }
        pp_result[i] = p;

        let mut q = PQ[6];
        for j in (0..6).rev() {
            q = q * z + PQ[j];
        }
        pq_result[i] = q;
    }

    (pp_result, pq_result)
}

/// Asymptotic P, Q corrections for J1/Y1 at large |x| (f32).
fn j1_asymptotic_pq_f32(inv_x2: &ArrayView1<f32>) -> (Array1<f32>, Array1<f32>) {
    let len = inv_x2.len();
    let mut pp_result = Array1::zeros(len);
    let mut pq_result = Array1::zeros(len);

    const PP: [f32; 5] = [
        7.62125616208173112003e-04,
        7.31397056940849243622e-02,
        1.12719608129684260397e+00,
        5.11207951146461568876e+00,
        1.00000000000000000254e+00,
    ];
    const PQ: [f32; 5] = [
        5.71050241285120902666e-04,
        6.88948006001962595e-02,
        1.10514232634061696926e+00,
        5.07386386128601488557e+00,
        9.99999999999999997461e-01,
    ];

    let inv_x2_slice = inv_x2
        .as_slice()
        .expect("j1_asymptotic_pq_f32: inv_x2 must be contiguous");

    for i in 0..len {
        let z = inv_x2_slice[i];
        let mut p = PP[4];
        for j in (0..4).rev() {
            p = p * z + PP[j];
        }
        pp_result[i] = p;

        let mut q = PQ[4];
        for j in (0..4).rev() {
            q = q * z + PQ[j];
        }
        pq_result[i] = q;
    }

    (pp_result, pq_result)
}

/// Y0(x) for small x (0 < x <= 8) using polynomial approximation (f64).
/// Y0(x) = (2/pi)*J0(x)*ln(x/2) + R(x^2)/S(x^2)
#[inline]
fn y0_small_f64(x: f64) -> f64 {
    // Use scalar function for maximum accuracy in the small-argument region
    crate::bessel::y0(x)
}

/// Y0(x) for small x (f32).
#[inline]
fn y0_small_f32(x: f32) -> f32 {
    crate::bessel::y0(x as f64) as f32
}

/// Y1(x) for small x (0 < x <= 8) (f64).
#[inline]
fn y1_small_f64(x: f64) -> f64 {
    crate::bessel::y1(x)
}

/// Y1(x) for small x (f32).
#[inline]
fn y1_small_f32(x: f32) -> f32 {
    crate::bessel::y1(x as f64) as f32
}