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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
//! Fresnel integrals
//!
//! This module provides implementations of the Fresnel integrals S(x) and C(x).
//! These integrals arise in optics and electromagnetics, particularly in the
//! study of diffraction patterns and are defined as:
//!
//! S(x) = ∫_0_^x sin(πt²/2) dt
//! C(x) = ∫_0_^x cos(πt²/2) dt
//!
//! There are also modified Fresnel integrals that are used in certain applications.
use scirs2_core::numeric::Complex64;
use scirs2_core::numeric::Zero;
use std::f64::consts::PI;
use crate::error::{SpecialError, SpecialResult};
/// Compute the Fresnel sine and cosine integrals.
///
/// # Definition
///
/// The Fresnel integrals are defined as:
///
/// S(x) = ∫_0_^x sin(πt²/2) dt
/// C(x) = ∫_0_^x cos(πt²/2) dt
///
/// # Arguments
///
/// * `x` - Real or complex argument
///
/// # Returns
///
/// * A tuple (S(x), C(x)) containing the values of the Fresnel sine and cosine integrals
///
/// # Examples
///
/// ```
/// use scirs2_special::fresnel;
///
/// let (s, c) = fresnel(1.0).expect("fresnel failed");
/// println!("S(1.0) = {}, C(1.0) = {}", s, c);
/// ```
#[allow(dead_code)]
pub fn fresnel(x: f64) -> SpecialResult<(f64, f64)> {
if x.is_nan() {
return Err(SpecialError::DomainError(
"NaN input to fresnel".to_string(),
));
}
if x == 0.0 {
return Ok((0.0, 0.0));
}
// For x with large magnitude, use the asymptotic form
if x.abs() > 6.0 {
let (s, c) = fresnel_asymptotic(x)?;
return Ok((s, c));
}
// For small to moderate x, use power series or auxiliary functions
fresnel_power_series(x)
}
/// Compute the Fresnel sine and cosine integrals for complex argument.
///
/// # Arguments
///
/// * `z` - Complex argument
///
/// # Returns
///
/// * A tuple (S(z), C(z)) containing the complex values of the Fresnel sine and cosine integrals
///
/// # Examples
///
/// ```
/// use scirs2_special::fresnel_complex;
/// use scirs2_core::numeric::Complex64;
///
/// let z = Complex64::new(1.0, 0.5);
/// let (s, c) = fresnel_complex(z).expect("fresnel_complex failed");
/// println!("S({} + {}i) = {} + {}i", z.re, z.im, s.re, s.im);
/// println!("C({} + {}i) = {} + {}i", z.re, z.im, c.re, c.im);
/// ```
#[allow(dead_code)]
pub fn fresnel_complex(z: Complex64) -> SpecialResult<(Complex64, Complex64)> {
if z.is_nan() {
return Err(SpecialError::DomainError(
"NaN input to fresnel_complex".to_string(),
));
}
if z.is_zero() {
return Ok((Complex64::new(0.0, 0.0), Complex64::new(0.0, 0.0)));
}
// For z with large magnitude, use the asymptotic form
if z.norm() > 6.0 {
let (s, c) = fresnel_complex_asymptotic(z)?;
return Ok((s, c));
}
// For small to moderate z, use power series
fresnel_complex_power_series(z)
}
/// Implementation of Fresnel integrals using power series.
///
/// Uses the standard Taylor series:
/// S(x) = sum_{n=0}^inf (-1)^n * (pi/2)^(2n+1) * x^(4n+3) / ((2n+1)! * (4n+3))
/// C(x) = sum_{n=0}^inf (-1)^n * (pi/2)^(2n) * x^(4n+1) / ((2n)! * (4n+1))
#[allow(dead_code)]
fn fresnel_power_series(x: f64) -> SpecialResult<(f64, f64)> {
let sign = x.signum();
let ax = x.abs();
// Special case for very small x to avoid underflow
if ax < 1e-100 {
return Ok((0.0, 0.0));
}
let pi_half = PI / 2.0;
let t = pi_half * ax * ax;
// For the series, compute in terms of t = pi*x^2/2
// S(x) = x * sum_{n=0}^inf (-t)^n * t / ((2n+1)*(4n+3)) -- not quite, use direct approach
//
// Direct series:
// S(x) = sum_{n=0}^inf (-1)^n (pi/2)^{2n+1} x^{4n+3} / ((2n+1)! (4n+3))
// C(x) = sum_{n=0}^inf (-1)^n (pi/2)^{2n} x^{4n+1} / ((2n)! (4n+1))
//
// Rearranged for stable computation:
// S(x) = x^3 * pi/2 * sum_{n=0} (-1)^n (pi*x^2/2)^{2n} / ((2n+1)! (4n+3))
// C(x) = x * sum_{n=0} (-1)^n (pi*x^2/2)^{2n} / ((2n)! (4n+1))
// Use the t-based formulation for stability
let t2 = t * t; // (pi*x^2/2)^2
// Compute C(x)
let mut c_sum = 0.0;
let mut c_term = 1.0; // n=0 term coefficient: 1 / (0! * 1) = 1
for n in 0..50 {
let denom = (4 * n + 1) as f64;
c_sum += c_term / denom;
// Prepare for next term: multiply by -t^2 / ((2n+1)*(2n+2))
let next_factor = -t2 / (((2 * n + 1) * (2 * n + 2)) as f64);
c_term *= next_factor;
if c_term.abs() / denom < 1e-16 * c_sum.abs().max(1e-300) {
break;
}
}
let c = ax * c_sum;
// Compute S(x)
let mut s_sum = 0.0;
let mut s_term = 1.0; // n=0 term coefficient: 1 / (1! * 3) but we factor out t*x below
for n in 0..50 {
let denom = (4 * n + 3) as f64;
s_sum += s_term / denom;
// Prepare for next term: multiply by -t^2 / ((2n+2)*(2n+3))
let next_factor = -t2 / (((2 * n + 2) * (2 * n + 3)) as f64);
s_term *= next_factor;
if s_term.abs() / denom < 1e-16 * s_sum.abs().max(1e-300) {
break;
}
}
let s = ax * t * s_sum;
Ok((sign * s, sign * c))
}
/// Implementation of Fresnel integrals using asymptotic expansions for large x.
#[allow(dead_code)]
fn fresnel_asymptotic(x: f64) -> SpecialResult<(f64, f64)> {
let sign = x.signum();
let x = x.abs();
// Special case for extremely large x
if x > 1e100 {
// For extremely large x, the Fresnel integrals approach 1/2
return Ok((sign * 0.5, sign * 0.5));
}
// For large x, the Fresnel integrals approach 1/2
// S(x) → 1/2 - f(x)cos(πx²/2) - g(x)sin(πx²/2)
// C(x) → 1/2 + f(x)sin(πx²/2) - g(x)cos(πx²/2)
// where f(x) and g(x) are asymptotic series
// Use a scaled approach for very large x to avoid overflow in x²
let z = if x > 1e7 {
// For very large x, compute z carefully to avoid overflow
let scaled_x = x / 1e7;
PI * scaled_x * scaled_x * 1e14 / 2.0
} else {
PI * x * x / 2.0
};
// The argument may be so large that z cannot be represented accurately
// In that case, simplify the computation by modding out the periods of sine and cosine
let reduced_z = if z > 1e10 {
// For extremely large z, reduce to principal values
let two_pi = 2.0 * PI;
z % two_pi
} else {
z
};
// Compute sine and cosine of the reduced argument
let sin_z = reduced_z.sin();
let cos_z = reduced_z.cos();
// Different strategies based on magnitude of x for stability
if x > 20.0 {
// For very large x, use a more accurate asymptotic form
// that avoids potential cancellation errors
// Compute just the first few terms of the asymptotic series
// This avoids divergence issues with asymptotic series for large orders
let f_first_term = 1.0 / (PI * x);
let g_first_term = 1.0 / (PI * 3.0 * 2.0 * z); // First term of g series
// For extremely large x, the higher-order terms are negligible
let s = 0.5 - f_first_term * cos_z - g_first_term * sin_z;
let c = 0.5 + f_first_term * sin_z - g_first_term * cos_z;
return Ok((sign * s, sign * c));
}
// For moderately large x, compute more terms of the series
let z2 = z * z;
let z2_inv = 1.0 / z2;
// Initialize with leading terms
let mut f = 1.0 / (PI * x);
let mut g = 0.0;
// Keep track of previous sums for convergence monitoring
let mut prev_f = f;
let mut prev_g = g;
let mut num_stable_terms = 0;
// Asymptotic series for f(x) and g(x) with enhanced stability
for k in 1..25 {
// Extended series for better accuracy
// Compute terms carefully to avoid overflow in large powers
let k_f64 = k as f64;
// Avoid direct power calculation which could overflow
// Instead, build up the power by multiplication
let mut z2_pow_k: f64 = z2_inv; // Start with (1/z2)
for _ in 1..k {
z2_pow_k *= z2_inv; // Multiply by (1/z2) k-1 more times
// Check for underflow
if z2_pow_k.abs() < 1e-300 {
break; // Underflow, further terms are negligible
}
}
// Calculate f and g terms with improved numerical stability
let f_term =
if k % 2 == 1 { -1.0 } else { 1.0 } * (4.0 * k_f64 - 1.0) * z2_pow_k / (PI * x);
let g_term = if k % 2 == 1 { -1.0 } else { 1.0 } * (4.0 * k_f64 + 1.0) * z2_pow_k
/ ((2.0 * k_f64 + 1.0) * PI);
// Add terms to the sums
f += f_term;
g += g_term;
// Multiple convergence criteria for better stability
// Absolute tolerance
let abs_tol = 1e-15;
// Relative tolerance
let f_rel_tol = 1e-15 * f.abs().max(1e-300);
let g_rel_tol = 1e-15 * g.abs().max(1e-300);
// Check for convergence
if f_term.abs() < abs_tol && g_term.abs() < abs_tol {
break; // Terms are absolutely small
}
if f_term.abs() < f_rel_tol && g_term.abs() < g_rel_tol {
break; // Terms are relatively small
}
// Check if sums are stabilizing (not changing significantly)
if (f - prev_f).abs() < f_rel_tol && (g - prev_g).abs() < g_rel_tol {
num_stable_terms += 1;
if num_stable_terms > 2 {
break; // Sums have stabilized
}
} else {
num_stable_terms = 0;
}
// Check for divergence (which can happen with asymptotic series)
if f_term.abs() > 100.0 * prev_f.abs() || g_term.abs() > 100.0 * prev_g.abs() {
// Series is starting to diverge, so use the previous sum
f = prev_f;
g = prev_g;
break;
}
prev_f = f;
prev_g = g;
}
// Compute the Fresnel integrals
let s = 0.5 - f * cos_z - g * sin_z;
let c = 0.5 + f * sin_z - g * cos_z;
// Apply the sign
Ok((sign * s, sign * c))
}
/// Implementation of complex Fresnel integrals using power series.
#[allow(dead_code)]
fn fresnel_complex_power_series(z: Complex64) -> SpecialResult<(Complex64, Complex64)> {
// Special case for very small |z|
if z.norm() < 1e-100 {
return Ok((Complex64::new(0.0, 0.0), Complex64::new(0.0, 0.0)));
}
// Use the same approach as the real-valued fresnel_power_series but with complex z.
// The Fresnel integrals are:
// C(z) = integral_0^z cos(pi*t^2/2) dt
// S(z) = integral_0^z sin(pi*t^2/2) dt
//
// Taylor series with t = pi*z^2/2:
// C(z) = z * sum_{n=0}^inf (-1)^n t^{2n} / ((2n)! * (4n+1))
// S(z) = z * t * sum_{n=0}^inf (-1)^n t^{2n} / ((2n+1)! * (4n+3))
//
// Using recurrence for the factorial-weighted terms.
let pi_half = Complex64::new(PI / 2.0, 0.0);
let t = pi_half * z * z;
let t2 = t * t;
// Compute C(z)
let mut c_sum = Complex64::new(0.0, 0.0);
let mut c_term = Complex64::new(1.0, 0.0);
for n in 0..80 {
let denom = (4 * n + 1) as f64;
c_sum += c_term / denom;
// Next term: multiply by -t^2 / ((2n+1)*(2n+2))
let next_factor = -t2 / Complex64::new(((2 * n + 1) * (2 * n + 2)) as f64, 0.0);
c_term *= next_factor;
if !c_term.is_finite() {
break;
}
if c_term.norm() / denom < 1e-16 * c_sum.norm().max(1e-300) && n > 3 {
break;
}
}
let c = z * c_sum;
// Compute S(z)
let mut s_sum = Complex64::new(0.0, 0.0);
let mut s_term = Complex64::new(1.0, 0.0);
for n in 0..80 {
let denom = (4 * n + 3) as f64;
s_sum += s_term / denom;
// Next term: multiply by -t^2 / ((2n+2)*(2n+3))
let next_factor = -t2 / Complex64::new(((2 * n + 2) * (2 * n + 3)) as f64, 0.0);
s_term *= next_factor;
if !s_term.is_finite() {
break;
}
if s_term.norm() / denom < 1e-16 * s_sum.norm().max(1e-300) && n > 3 {
break;
}
}
let s = z * t * s_sum;
Ok((s, c))
}
/// Implementation of complex Fresnel integrals using asymptotic expansions.
#[allow(dead_code)]
fn fresnel_complex_asymptotic(z: Complex64) -> SpecialResult<(Complex64, Complex64)> {
// Special cases for extreme values
if !z.is_finite() {
return Err(SpecialError::DomainError(
"Infinite or NaN input to fresnel_complex_asymptotic".to_string(),
));
}
// For extremely large |z|, directly return the limit
if z.norm() > 1e100 {
return Ok((Complex64::new(0.5, 0.0), Complex64::new(0.5, 0.0)));
}
// Calculate with appropriate scaling to avoid overflow
let pi_z2_half = if z.norm() > 1e7 {
// For very large z, compute carefully to avoid overflow in z²
let scaled_z = z / 1e7;
PI * scaled_z * scaled_z * 1e14 / 2.0
} else {
PI * z * z / 2.0
};
// For very large arguments, reduce trigonometric arguments to principal values
let reduced_pi_z2_half = if pi_z2_half.norm() > 1e10 {
let two_pi = Complex64::new(2.0 * PI, 0.0);
// Complex modulo operation
let n = (pi_z2_half / two_pi).re.floor();
pi_z2_half - two_pi * Complex64::new(n, 0.0)
} else {
pi_z2_half
};
// Compute sine and cosine of the reduced argument
let sin_pi_z2_half = reduced_pi_z2_half.sin();
let cos_pi_z2_half = reduced_pi_z2_half.cos();
// For very large |z|, use simplified asymptotic form
if z.norm() > 20.0 {
// Just use the first term of the asymptotic series
let f_first_term = Complex64::new(1.0, 0.0) / (PI * z);
// g is numerically smaller than f for large |z|
let g_first_term = f_first_term / (3.0 * pi_z2_half);
// Calculate the Fresnel integrals with just these first terms
let half = Complex64::new(0.5, 0.0);
let s = half - f_first_term * cos_pi_z2_half - g_first_term * sin_pi_z2_half;
let c = half + f_first_term * sin_pi_z2_half - g_first_term * cos_pi_z2_half;
return Ok((s, c));
}
// For moderately large |z|, compute more terms of the asymptotic series
let pi_z2_half_sq = pi_z2_half * pi_z2_half;
// Initialize with the first terms
let mut f = Complex64::new(1.0, 0.0) / (PI * z);
let mut g = Complex64::new(0.0, 0.0);
// Track previous sums for convergence monitoring
let mut prev_f = f;
let mut prev_g = g;
let mut num_stable_terms = 0;
// Asymptotic series with enhanced stability
for k in 1..20 {
// Use safer term calculation
let k_f64 = k as f64;
// Compute powers more carefully using division instead of power
let mut pi_z2_half_sq_pow_k = Complex64::new(1.0, 0.0);
for _ in 0..k {
pi_z2_half_sq_pow_k /= pi_z2_half_sq;
// Check for underflow/overflow
if !pi_z2_half_sq_pow_k.is_finite() || pi_z2_half_sq_pow_k.norm() < 1e-300 {
break;
}
}
// Alternating sign based on k
let sign = if k % 2 == 1 { -1.0 } else { 1.0 };
// Calculate f term
let f_term = sign * (4.0 * k_f64 - 1.0) * pi_z2_half_sq_pow_k / (PI * z);
// Calculate g term
let g_term = sign * (4.0 * k_f64 + 1.0) * pi_z2_half_sq_pow_k / ((2.0 * k_f64 + 1.0) * PI);
// Only add terms if they're finite (to handle potential overflow/underflow)
if f_term.is_finite() {
f += f_term;
}
if g_term.is_finite() {
g += g_term;
}
// Multiple convergence checks
let f_norm = f_term.norm();
let g_norm = g_term.norm();
let f_sum_norm = f.norm().max(1e-300);
let g_sum_norm = g.norm().max(1e-300);
// Check for absolute and relative convergence
if f_norm < 1e-15 && g_norm < 1e-15 {
break; // Both terms are absolutely small
}
if f_norm < 1e-15 * f_sum_norm && g_norm < 1e-15 * g_sum_norm {
break; // Both terms are relatively small
}
// Check if sums are stabilizing
if (f - prev_f).norm() < 1e-15 * f_sum_norm && (g - prev_g).norm() < 1e-15 * g_sum_norm {
num_stable_terms += 1;
if num_stable_terms > 2 {
break; // Sums have stabilized
}
} else {
num_stable_terms = 0;
}
// Check for potential divergence
if f_norm > 100.0 * prev_f.norm() || g_norm > 100.0 * prev_g.norm() {
// Series is starting to diverge, use previous sum
f = prev_f;
g = prev_g;
break;
}
prev_f = f;
prev_g = g;
}
// Compute the Fresnel integrals
let half = Complex64::new(0.5, 0.0);
let s = half - f * cos_pi_z2_half - g * sin_pi_z2_half;
let c = half + f * sin_pi_z2_half - g * cos_pi_z2_half;
// Final check for numerical issues
if !s.is_finite() || !c.is_finite() {
// Fallback to the simplest approximation for large |z|
let s_approx = Complex64::new(0.5, 0.0);
let c_approx = Complex64::new(0.5, 0.0);
return Ok((s_approx, c_approx));
}
Ok((s, c))
}
/// Compute the Fresnel sine integral.
///
/// # Definition
///
/// The Fresnel sine integral is defined as:
///
/// S(x) = ∫_0_^x sin(πt²/2) dt
///
/// # Arguments
///
/// * `x` - Real argument
///
/// # Returns
///
/// * Value of the Fresnel sine integral S(x)
///
/// # Examples
///
/// ```
/// use scirs2_special::fresnels;
///
/// let s = fresnels(1.0).expect("fresnels failed");
/// println!("S(1.0) = {}", s);
/// ```
#[allow(dead_code)]
pub fn fresnels(x: f64) -> SpecialResult<f64> {
let (s, _) = fresnel(x)?;
Ok(s)
}
/// Compute the Fresnel cosine integral.
///
/// # Definition
///
/// The Fresnel cosine integral is defined as:
///
/// C(x) = ∫_0_^x cos(πt²/2) dt
///
/// # Arguments
///
/// * `x` - Real argument
///
/// # Returns
///
/// * Value of the Fresnel cosine integral C(x)
///
/// # Examples
///
/// ```
/// use scirs2_special::fresnelc;
///
/// let c = fresnelc(1.0).expect("fresnelc failed");
/// println!("C(1.0) = {}", c);
/// ```
#[allow(dead_code)]
pub fn fresnelc(x: f64) -> SpecialResult<f64> {
let (_, c) = fresnel(x)?;
Ok(c)
}
/// Compute the modified Fresnel plus integrals.
///
/// # Definition
///
/// The modified Fresnel plus integrals are defined as:
///
/// F₊(x) = ∫_x^∞ exp(it²) dt
/// K₊(x) = 1/√π · exp(-i(x² + π/4)) · F₊(x)
///
/// # Arguments
///
/// * `x` - Real argument
///
/// # Returns
///
/// * A tuple (F₊(x), K₊(x)) containing the values of the modified Fresnel plus integrals
///
/// # Examples
///
/// ```
/// use scirs2_special::mod_fresnel_plus;
///
/// let (f_plus, k_plus) = mod_fresnel_plus(1.0).expect("mod_fresnel_plus failed");
/// println!("F₊(1.0) = {} + {}i", f_plus.re, f_plus.im);
/// println!("K₊(1.0) = {} + {}i", k_plus.re, k_plus.im);
/// ```
#[allow(dead_code)]
pub fn mod_fresnel_plus(x: f64) -> SpecialResult<(Complex64, Complex64)> {
if x.is_nan() {
return Err(SpecialError::DomainError(
"NaN input to mod_fresnel_plus".to_string(),
));
}
// Special case for extremely small x
if x.abs() < 1e-100 {
// For x ≈ 0, F₊(0) approaches √π·e^(iπ/4)/2
let sqrt_pi = PI.sqrt();
let exp_i_pi_4 = Complex64::new(1.0, 0.0) * Complex64::new(0.5, 0.5).sqrt();
let f_plus_0 = sqrt_pi * exp_i_pi_4 / 2.0;
// K₊(0) ≈ 1/2
let k_plus_0 = Complex64::new(0.5, 0.0);
return Ok((f_plus_0, k_plus_0));
}
// Special case for extremely large x
if x.abs() > 1e100 {
// For |x| → ∞, F₊(x) → 0 and K₊(x) → 0
let zero = Complex64::new(0.0, 0.0);
return Ok((zero, zero));
}
// The modified Fresnel plus integrals can be expressed in terms of the standard Fresnel integrals
let z = x.abs();
// Compute auxiliary values (Fresnel integrals)
let (s, c) = fresnel(z)?;
let sqrt_pi = PI.sqrt();
let sqrt_pi_inv = 1.0 / sqrt_pi;
// For large z, compute the phase carefully to avoid overflow in z²
// exp(±i(z² + π/4))
let phase = if z > 1e7 {
// Scale to avoid overflow
let scaled_z = z / 1e7;
let scaled_z_sq = scaled_z * scaled_z * 1e14;
Complex64::new(0.0, scaled_z_sq + PI / 4.0)
} else {
Complex64::new(0.0, z * z + PI / 4.0)
};
// Check for potential overflow in the exponential
// If the imaginary part of phase is very large, reduce it modulo 2Ï€
let reduced_phase = if phase.im.abs() > 100.0 {
let two_pi = 2.0 * PI;
let n = (phase.im / two_pi).floor();
Complex64::new(phase.re, phase.im - n * two_pi)
} else {
phase
};
let exp_phase = reduced_phase.exp();
let exp_i_pi_4 = Complex64::new(0.5, 0.5).sqrt(); // e^(iπ/4) = (1+i)/√2
// Compute F₊(x) with improved numerical stability
let f_plus = if x >= 0.0 {
// For positive x: F₊(x) = (1/2 - C(x) - iS(x))·√π·exp(iπ/4)
// Handle potential cancellation in 0.5 - c for large x
// For large x, both c and s approach 0.5, so we compute the difference directly
let halfminus_c = if z > 10.0 {
// For large z, compute the difference using the asymptotic series directly
let _z_sq = z * z;
let pi_z = PI * z;
1.0 / (2.0 * pi_z) * z.cos() // First term of asymptotic expansion
} else {
0.5 - c
};
// Similarly for s approaching 0.5
let minus_s = if z > 10.0 {
let _z_sq = z * z;
let pi_z = PI * z;
-0.5 + 1.0 / (2.0 * pi_z) * z.sin() // First term of asymptotic expansion
} else {
-s
};
let halfminus_cminus_is = Complex64::new(halfminus_c, minus_s);
halfminus_cminus_is * sqrt_pi * exp_i_pi_4
} else {
// For negative x: F₊(-x) = (1/2 + C(x) + iS(x))·√π·exp(iπ/4)
// Similar improved calculations for -x
let half_plus_c = if z > 10.0 {
let _z_sq = z * z;
let pi_z = PI * z;
0.5 + 1.0 / (2.0 * pi_z) * z.cos()
} else {
0.5 + c
};
let plus_s = if z > 10.0 {
let _z_sq = z * z;
let pi_z = PI * z;
0.5 - 1.0 / (2.0 * pi_z) * z.sin()
} else {
s
};
let half_plus_c_plus_is = Complex64::new(half_plus_c, plus_s);
half_plus_c_plus_is * sqrt_pi * exp_i_pi_4
};
// Compute K₊(x) = exp(-i(x² + π/4)) · F₊(x) / √π with careful multiplication
// Use intermediate variable to avoid catastrophic cancellation
let k_plus_unnormalized = exp_phase.conj() * f_plus;
let k_plus = k_plus_unnormalized * sqrt_pi_inv;
// Final check for numerical stability
if !f_plus.is_finite() || !k_plus.is_finite() {
// Fallback to asymptotic approximations for very large arguments
if x.abs() > 10.0 {
// For large |x|, the integrals decay like 1/x
let decay_factor = 1.0 / x.abs();
let f_plus_approx = Complex64::new(decay_factor, decay_factor);
let k_plus_approx = Complex64::new(decay_factor, -decay_factor) * sqrt_pi_inv;
return Ok((f_plus_approx, k_plus_approx));
}
}
Ok((f_plus, k_plus))
}
/// Compute the modified Fresnel minus integrals.
///
/// # Definition
///
/// The modified Fresnel minus integrals are defined as:
///
/// F₋(x) = ∫_x^∞ exp(-it²) dt
/// K₋(x) = 1/√π · exp(i(x² + π/4)) · F₋(x)
///
/// # Arguments
///
/// * `x` - Real argument
///
/// # Returns
///
/// * A tuple (Fâ‚‹(x), Kâ‚‹(x)) containing the values of the modified Fresnel minus integrals
///
/// # Examples
///
/// ```
/// use scirs2_special::mod_fresnelminus;
///
/// let (fminus, kminus) = mod_fresnelminus(1.0).expect("mod_fresnelminus failed");
/// println!("Fâ‚‹(1.0) = {} + {}i", fminus.re, fminus.im);
/// println!("Kâ‚‹(1.0) = {} + {}i", kminus.re, kminus.im);
/// ```
#[allow(dead_code)]
pub fn mod_fresnelminus(x: f64) -> SpecialResult<(Complex64, Complex64)> {
if x.is_nan() {
return Err(SpecialError::DomainError(
"NaN input to mod_fresnelminus".to_string(),
));
}
// Special case for extremely small x
if x.abs() < 1e-100 {
// For x ≈ 0, F₋(0) approaches √π·e^(-iπ/4)/2
let sqrt_pi = PI.sqrt();
let expminus_i_pi_4 = Complex64::new(1.0, 0.0) * Complex64::new(0.5, -0.5).sqrt();
let fminus_0 = sqrt_pi * expminus_i_pi_4 / 2.0;
// K₋(0) ≈ 1/2
let kminus_0 = Complex64::new(0.5, 0.0);
return Ok((fminus_0, kminus_0));
}
// Special case for extremely large x
if x.abs() > 1e100 {
// For |x| → ∞, F₋(x) → 0 and K₋(x) → 0
let zero = Complex64::new(0.0, 0.0);
return Ok((zero, zero));
}
// The modified Fresnel minus integrals can be expressed in terms of the standard Fresnel integrals
let z = x.abs();
// Compute auxiliary values (Fresnel integrals)
let (s, c) = fresnel(z)?;
let sqrt_pi = PI.sqrt();
let sqrt_pi_inv = 1.0 / sqrt_pi;
// For large z, compute the phase carefully to avoid overflow in z²
// exp(±i(z² + π/4))
let phase = if z > 1e7 {
// Scale to avoid overflow
let scaled_z = z / 1e7;
let scaled_z_sq = scaled_z * scaled_z * 1e14;
Complex64::new(0.0, scaled_z_sq + PI / 4.0)
} else {
Complex64::new(0.0, z * z + PI / 4.0)
};
// Check for potential overflow in the exponential
// If the imaginary part of phase is very large, reduce it modulo 2Ï€
let reduced_phase = if phase.im.abs() > 100.0 {
let two_pi = 2.0 * PI;
let n = (phase.im / two_pi).floor();
Complex64::new(phase.re, phase.im - n * two_pi)
} else {
phase
};
let exp_phase = reduced_phase.exp();
let expminus_i_pi_4 = Complex64::new(0.5, -0.5).sqrt(); // e^(-iπ/4) = (1-i)/√2
// Compute Fâ‚‹(x) with improved numerical stability
let fminus = if x >= 0.0 {
// For positive x: F₋(x) = (1/2 - C(x) + iS(x))·√π·exp(-iπ/4)
// Handle potential cancellation in 0.5 - c for large x
// For large x, both c and s approach 0.5, so we compute the difference directly
let halfminus_c = if z > 10.0 {
// For large z, compute the difference using the asymptotic series directly
let pi_z = PI * z;
1.0 / (2.0 * pi_z) * z.cos() // First term of asymptotic expansion
} else {
0.5 - c
};
// Similarly for s approaching 0.5
let plus_s = if z > 10.0 {
let pi_z = PI * z;
0.5 - 1.0 / (2.0 * pi_z) * z.sin() // First term of asymptotic expansion
} else {
s
};
let halfminus_c_plus_is = Complex64::new(halfminus_c, plus_s);
halfminus_c_plus_is * sqrt_pi * expminus_i_pi_4
} else {
// For negative x: F₋(-x) = (1/2 + C(x) - iS(x))·√π·exp(-iπ/4)
// Similar improved calculations for -x
let half_plus_c = if z > 10.0 {
let pi_z = PI * z;
0.5 + 1.0 / (2.0 * pi_z) * z.cos()
} else {
0.5 + c
};
let minus_s = if z > 10.0 {
let pi_z = PI * z;
-0.5 + 1.0 / (2.0 * pi_z) * z.sin()
} else {
-s
};
let half_plus_cminus_is = Complex64::new(half_plus_c, minus_s);
half_plus_cminus_is * sqrt_pi * expminus_i_pi_4
};
// Compute K₋(x) = exp(i(x² + π/4)) · F₋(x) / √π with careful multiplication
// Use intermediate variable to avoid catastrophic cancellation
let kminus_unnormalized = exp_phase * fminus;
let kminus = kminus_unnormalized * sqrt_pi_inv;
// Final check for numerical stability
if !fminus.is_finite() || !kminus.is_finite() {
// Fallback to asymptotic approximations for very large arguments
if x.abs() > 10.0 {
// For large |x|, the integrals decay like 1/x
let decay_factor = 1.0 / x.abs();
let fminus_approx = Complex64::new(decay_factor, -decay_factor);
let kminus_approx = Complex64::new(decay_factor, decay_factor) * sqrt_pi_inv;
return Ok((fminus_approx, kminus_approx));
}
}
Ok((fminus, kminus))
}
#[cfg(test)]
mod tests {
use super::*;
// ====== Fresnel S(x) and C(x) combined tests ======
#[test]
fn test_fresnel_at_zero() {
let (s, c) = fresnel(0.0).expect("fresnel(0) failed");
assert!((s - 0.0).abs() < 1e-14, "S(0) should be 0, got {s}");
assert!((c - 0.0).abs() < 1e-14, "C(0) should be 0, got {c}");
}
#[test]
fn test_fresnel_at_one() {
// Reference: S(1) ~ 0.438259147, C(1) ~ 0.779893400
let (s, c) = fresnel(1.0).expect("fresnel(1) failed");
assert!((s - 0.438_259_147).abs() < 1e-6, "S(1) ~ 0.438259, got {s}");
assert!((c - 0.779_893_400).abs() < 1e-6, "C(1) ~ 0.779893, got {c}");
}
#[test]
fn test_fresnel_at_two() {
// Reference: S(2) ~ 0.343415, C(2) ~ 0.488253
let (s, c) = fresnel(2.0).expect("fresnel(2) failed");
assert!((s - 0.343_415).abs() < 1e-4, "S(2) ~ 0.3434, got {s}");
assert!((c - 0.488_253).abs() < 1e-4, "C(2) ~ 0.4883, got {c}");
}
#[test]
fn test_fresnel_large_x_approaches_half() {
// For large x, S(x) and C(x) should approach 0.5
let (s, c) = fresnel(50.0).expect("fresnel(50) failed");
assert!((s - 0.5).abs() < 0.05, "S(50) should be near 0.5, got {s}");
assert!((c - 0.5).abs() < 0.05, "C(50) should be near 0.5, got {c}");
}
#[test]
fn test_fresnel_odd_symmetry() {
// S(-x) = -S(x), C(-x) = -C(x) (odd functions)
let (s_pos, c_pos) = fresnel(1.5).expect("fresnel(1.5) failed");
let (s_neg, c_neg) = fresnel(-1.5).expect("fresnel(-1.5) failed");
assert!(
(s_neg + s_pos).abs() < 1e-10,
"S should be odd: S(1.5)={s_pos}, S(-1.5)={s_neg}"
);
assert!(
(c_neg + c_pos).abs() < 1e-10,
"C should be odd: C(1.5)={c_pos}, C(-1.5)={c_neg}"
);
}
#[test]
fn test_fresnel_nan_input() {
let result = fresnel(f64::NAN);
assert!(
result.is_err(),
"fresnel with NaN input should return error"
);
}
// ====== fresnels tests ======
#[test]
fn test_fresnels_at_zero() {
let s = fresnels(0.0).expect("fresnels(0) failed");
assert!((s - 0.0).abs() < 1e-14, "S(0) should be 0, got {s}");
}
#[test]
fn test_fresnels_at_one() {
let s = fresnels(1.0).expect("fresnels(1) failed");
assert!((s - 0.438_259_147).abs() < 1e-6, "S(1) ~ 0.438259, got {s}");
}
#[test]
fn test_fresnels_matches_fresnel() {
let s1 = fresnels(2.5).expect("fresnels(2.5) failed");
let (s2, _) = fresnel(2.5).expect("fresnel(2.5) failed");
assert!(
(s1 - s2).abs() < 1e-10,
"fresnels should match fresnel: {s1} vs {s2}"
);
}
#[test]
fn test_fresnels_nan() {
let result = fresnels(f64::NAN);
assert!(
result.is_err(),
"fresnels with NaN input should return error"
);
}
#[test]
fn test_fresnels_negative() {
let s_pos = fresnels(1.0).expect("fresnels(1) failed");
let s_neg = fresnels(-1.0).expect("fresnels(-1) failed");
assert!((s_neg + s_pos).abs() < 1e-10, "S should be odd function");
}
// ====== fresnelc tests ======
#[test]
fn test_fresnelc_at_zero() {
let c = fresnelc(0.0).expect("fresnelc(0) failed");
assert!((c - 0.0).abs() < 1e-14, "C(0) should be 0, got {c}");
}
#[test]
fn test_fresnelc_at_one() {
let c = fresnelc(1.0).expect("fresnelc(1) failed");
assert!((c - 0.779_893_400).abs() < 1e-6, "C(1) ~ 0.779893, got {c}");
}
#[test]
fn test_fresnelc_matches_fresnel() {
let c1 = fresnelc(2.5).expect("fresnelc(2.5) failed");
let (_, c2) = fresnel(2.5).expect("fresnel(2.5) failed");
assert!(
(c1 - c2).abs() < 1e-10,
"fresnelc should match fresnel: {c1} vs {c2}"
);
}
#[test]
fn test_fresnelc_nan() {
let result = fresnelc(f64::NAN);
assert!(
result.is_err(),
"fresnelc with NaN input should return error"
);
}
#[test]
fn test_fresnelc_negative() {
let c_pos = fresnelc(1.0).expect("fresnelc(1) failed");
let c_neg = fresnelc(-1.0).expect("fresnelc(-1) failed");
assert!((c_neg + c_pos).abs() < 1e-10, "C should be odd function");
}
// ====== fresnel_complex tests ======
#[test]
fn test_fresnel_complex_real_axis() {
// On the real axis, fresnel_complex should match fresnel
let z = Complex64::new(1.0, 0.0);
let (s_c, c_c) = fresnel_complex(z).expect("fresnel_complex failed");
let (s_r, c_r) = fresnel(1.0).expect("fresnel failed");
assert!(
(s_c.re - s_r).abs() < 1e-8,
"complex fresnel S on real axis should match: {s_c} vs {s_r}"
);
assert!(
s_c.im.abs() < 1e-8,
"imaginary part of S on real axis should be ~0"
);
assert!(
(c_c.re - c_r).abs() < 1e-8,
"complex fresnel C on real axis should match: {c_c} vs {c_r}"
);
}
#[test]
fn test_fresnel_complex_at_zero() {
let z = Complex64::new(0.0, 0.0);
let (s, c) = fresnel_complex(z).expect("fresnel_complex(0) failed");
assert!(s.norm() < 1e-14, "S(0) should be 0");
assert!(c.norm() < 1e-14, "C(0) should be 0");
}
#[test]
fn test_fresnel_complex_purely_imaginary() {
let z = Complex64::new(0.0, 1.0);
let (s, c) = fresnel_complex(z).expect("fresnel_complex(i) failed");
assert!(s.is_finite(), "S(i) should be finite");
assert!(c.is_finite(), "C(i) should be finite");
}
#[test]
fn test_fresnel_complex_nan() {
let z = Complex64::new(f64::NAN, 0.0);
let result = fresnel_complex(z);
assert!(
result.is_err(),
"fresnel_complex with NaN should return error"
);
}
#[test]
fn test_fresnel_complex_moderate() {
let z = Complex64::new(1.0, 0.5);
let (s, c) = fresnel_complex(z).expect("fresnel_complex(1+0.5i) failed");
assert!(s.is_finite(), "S(1+0.5i) should be finite");
assert!(c.is_finite(), "C(1+0.5i) should be finite");
}
// ====== mod_fresnel_plus tests ======
#[test]
fn test_mod_fresnel_plus_at_zero() {
let (f_plus, k_plus) = mod_fresnel_plus(0.0).expect("mod_fresnel_plus(0) failed");
assert!(f_plus.is_finite(), "F+(0) should be finite");
assert!(k_plus.is_finite(), "K+(0) should be finite");
}
#[test]
fn test_mod_fresnel_plus_at_one() {
let (f_plus, k_plus) = mod_fresnel_plus(1.0).expect("mod_fresnel_plus(1) failed");
assert!(f_plus.is_finite(), "F+(1) should be finite");
assert!(k_plus.is_finite(), "K+(1) should be finite");
}
#[test]
fn test_mod_fresnel_plus_moderate_x() {
let (f_plus, k_plus) = mod_fresnel_plus(5.0).expect("mod_fresnel_plus(5) failed");
assert!(f_plus.is_finite(), "F+(5) should be finite");
assert!(k_plus.is_finite(), "K+(5) should be finite");
}
#[test]
fn test_mod_fresnel_plus_negative() {
let (f_plus, k_plus) = mod_fresnel_plus(-1.0).expect("mod_fresnel_plus(-1) failed");
assert!(f_plus.is_finite(), "F+(-1) should be finite");
assert!(k_plus.is_finite(), "K+(-1) should be finite");
}
#[test]
fn test_mod_fresnel_plus_large_x() {
let (f_plus, k_plus) = mod_fresnel_plus(20.0).expect("mod_fresnel_plus(20) failed");
assert!(f_plus.is_finite(), "F+(20) should be finite");
assert!(k_plus.is_finite(), "K+(20) should be finite");
}
// ====== mod_fresnelminus tests ======
#[test]
fn test_mod_fresnelminus_at_zero() {
let (fminus, kminus) = mod_fresnelminus(0.0).expect("mod_fresnelminus(0) failed");
assert!(fminus.is_finite(), "F-(0) should be finite");
assert!(kminus.is_finite(), "K-(0) should be finite");
}
#[test]
fn test_mod_fresnelminus_at_one() {
let (fminus, kminus) = mod_fresnelminus(1.0).expect("mod_fresnelminus(1) failed");
assert!(fminus.is_finite(), "F-(1) should be finite");
assert!(kminus.is_finite(), "K-(1) should be finite");
}
#[test]
fn test_mod_fresnelminus_moderate_x() {
let (fminus, kminus) = mod_fresnelminus(5.0).expect("mod_fresnelminus(5) failed");
assert!(fminus.is_finite(), "F-(5) should be finite");
assert!(kminus.is_finite(), "K-(5) should be finite");
}
#[test]
fn test_mod_fresnelminus_negative() {
let (fminus, kminus) = mod_fresnelminus(-1.0).expect("mod_fresnelminus(-1) failed");
assert!(fminus.is_finite(), "F-(-1) should be finite");
assert!(kminus.is_finite(), "K-(-1) should be finite");
}
#[test]
fn test_mod_fresnelminus_large_x() {
let (fminus, kminus) = mod_fresnelminus(20.0).expect("mod_fresnelminus(20) failed");
assert!(fminus.is_finite(), "F-(20) should be finite");
assert!(kminus.is_finite(), "K-(20) should be finite");
}
}