@@ -415,3 +415,80 @@ where
415
415
}
416
416
}
417
417
}
418
+
419
+ #[ cfg( test) ]
420
+ mod tests_cubic_spline_interpolation {
421
+ use super :: * ;
422
+ use RustQuant_utils :: { assert_approx_equal, RUSTQUANT_EPSILON } ;
423
+
424
+ #[ test]
425
+ fn test_natural_cubic_interpolation ( ) {
426
+
427
+ let xs: Vec < f64 > = vec ! [ 0. , 1. , 2. , 3. , 4. ] ;
428
+ let ys: Vec < f64 > = vec ! [ 0. , 1. , 16. , 81. , 256. ] ;
429
+
430
+ let mut interpolator: CubicSplineInterpolator < f64 , f64 > = CubicSplineInterpolator :: new ( xs, ys) . unwrap ( ) ;
431
+ let _ = interpolator. fit ( ) ;
432
+
433
+ assert_approx_equal ! (
434
+ 36.64909523809524 ,
435
+ interpolator. interpolate( 2.5 ) . unwrap( ) ,
436
+ RUSTQUANT_EPSILON
437
+ ) ;
438
+ }
439
+
440
+ #[ test]
441
+ fn test_natural_cubic_interpolation_dates ( ) {
442
+ let now: time:: OffsetDateTime = time:: OffsetDateTime :: now_utc ( ) ;
443
+
444
+ let xs: Vec < time:: OffsetDateTime > = vec ! [
445
+ now,
446
+ now + time:: Duration :: days( 1 ) ,
447
+ now + time:: Duration :: days( 2 ) ,
448
+ now + time:: Duration :: days( 3 ) ,
449
+ now + time:: Duration :: days( 4 ) ,
450
+ ] ;
451
+
452
+ let ys: Vec < f64 > = vec ! [ 0. , 1. , 16. , 81. , 256. ] ;
453
+
454
+ let mut interpolator: CubicSplineInterpolator < time:: OffsetDateTime , f64 > = CubicSplineInterpolator :: new ( xs. clone ( ) , ys) . unwrap ( ) ;
455
+ let _ = interpolator. fit ( ) ;
456
+
457
+ assert_approx_equal ! (
458
+ 36.64909523809524 ,
459
+ interpolator
460
+ . interpolate( xs[ 2 ] + time:: Duration :: hours( 12 ) )
461
+ . unwrap( ) ,
462
+ RUSTQUANT_EPSILON
463
+ ) ;
464
+ }
465
+
466
+ #[ test]
467
+ fn test_cubic_interpolation_out_of_range ( ) {
468
+ let xs: Vec < f64 > = vec ! [ 1. , 2. , 3. , 4. , 5. ] ;
469
+ let ys = vec ! [ 1. , 2. , 3. , 4. , 5. ] ;
470
+
471
+ let mut interpolator: CubicSplineInterpolator < f64 , f64 > = CubicSplineInterpolator :: new ( xs, ys) . unwrap ( ) ;
472
+ let _ = interpolator. fit ( ) ;
473
+
474
+ assert ! ( interpolator. interpolate( 6. ) . is_err( ) ) ;
475
+ }
476
+
477
+ #[ test]
478
+ fn test_cubic_interpolation_add_range_and_refit ( ) {
479
+ let xs: Vec < f64 > = vec ! [ 0. , 1. , 2. , 3. , 4. ] ;
480
+ let ys: Vec < f64 > = vec ! [ 0. , 1. , 16. , 81. , 256. ] ;
481
+
482
+ let mut interpolator: CubicSplineInterpolator < f64 , f64 > = CubicSplineInterpolator :: new ( xs, ys) . unwrap ( ) ;
483
+ let _ = interpolator. fit ( ) ;
484
+
485
+ interpolator. add_point ( ( 5.0 , 625.0 ) ) ;
486
+ let _ = interpolator. fit ( ) ;
487
+
488
+ assert_approx_equal ! (
489
+ 39.966361318634604 ,
490
+ interpolator. interpolate( 2.5 ) . unwrap( ) ,
491
+ RUSTQUANT_EPSILON
492
+ ) ;
493
+ }
494
+ }
0 commit comments