togo 0.7.2

A library for 2D geometry, providing geometric algorithms for intersection/distance between circular arcs/line segments.
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
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
#![allow(dead_code)]
#![deny(unused_results)]

use robust::{Coord, orient2d};

pub use crate::utils::almost_equal_as_int;
use crate::utils::{diff_of_prod, sum_of_prod};
use std::fmt::Display;
use std::ops;
use std::ops::{Div, Mul, Neg};

const ZERO: f64 = 0f64;

/// A 2D point with double precision floating point coordinates.
///
/// This is a fundamental data type used throughout the togo library
/// to represent positions and vectors in 2D space.
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// let p1 = point(3.0, 4.0);
/// let p2 = point(1.0, 2.0);
/// let sum = p1 + p2; // Point arithmetic is supported
/// ```
#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd)]
pub struct Point {
    /// X coordinate
    pub x: f64,
    /// Y coordinate  
    pub y: f64,
}

pub type Pointline = Vec<Point>;

impl Point {
    /// Creates a new point with the given coordinates.
    ///
    /// # Arguments
    ///
    /// * `x` - The x coordinate
    /// * `y` - The y coordinate
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p = Point::new(3.0, 4.0);
    /// assert_eq!(p.x, 3.0);
    /// assert_eq!(p.y, 4.0);
    /// ```
    pub fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }
}

/// Creates a new point with the given coordinates.
///
/// This is a convenience function equivalent to `Point::new(x, y)`.
///
/// # Arguments
///
/// * `x` - The x coordinate
/// * `y` - The y coordinate
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// let p = point(3.0, 4.0);
/// assert_eq!(p.x, 3.0);
/// assert_eq!(p.y, 4.0);
/// ```
#[inline]
#[must_use]
pub fn point(x: f64, y: f64) -> Point {
    Point::new(x, y)
}

/// Computes the 2D orientation test for three points.
///
/// This function determines the orientation of point `p` relative to the directed
/// line from point `a` to point `b`. It uses the robust `orient2d` predicate
/// which computes the sign of the determinant:
///
/// ```text
/// | ax  ay  1 |
/// | bx  by  1 |  
/// | px  py  1 |
/// ```
///
/// This is equivalent to twice the signed area of the triangle formed by the three points.
///
/// # Returns
///
/// * Positive value: `p` is to the left of the directed line from `a` to `b`
/// * Negative value: `p` is to the right of the directed line from `a` to `b`  
/// * Zero: The three points are collinear
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// let a = point(0.0, 0.0);
/// let b = point(1.0, 0.0);
///
/// // Point to the left of the line (positive orientation)
/// let p_left = point(0.5, 1.0);
/// assert!(points_order(a, b, p_left) > 0.0);
///
/// // Point to the right of the line (negative orientation)  
/// let p_right = point(0.5, -1.0);
/// assert!(points_order(a, b, p_right) < 0.0);
///
/// // Collinear point (zero orientation)
/// let p_collinear = point(0.5, 0.0);
/// assert_eq!(points_order(a, b, p_collinear), 0.0);
/// ```
#[must_use]
pub fn points_order(a: Point, b: Point, p: Point) -> f64 {
    let pa = Coord { x: a.x, y: a.y };
    let pb = Coord { x: b.x, y: b.y };
    let pp = Coord { x: p.x, y: p.y };
    orient2d(pa, pb, pp)
}

impl Display for Point {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{:.20}, {:.20}]", self.x, self.y)
    }
}

// #00027
// This approach uses a macro to reduce code duplication.
macro_rules! ImplBinaryOp {
    ($op_trait:ident, $op_func:ident, $op:tt) => {
        impl ops::$op_trait<Point> for Point {
            type Output = Point;
            #[inline]
            fn $op_func(self, rhs: Point) -> Self::Output {
                Point::new(self.x $op rhs.x, self.y $op rhs.y)
            }
        }

        impl ops::$op_trait<&Point> for Point {
            type Output = Point;
            #[inline]
            fn $op_func(self, rhs: &Point) -> Self::Output {
                Point::new(self.x $op rhs.x, self.y $op rhs.y)
            }
        }

        impl ops::$op_trait<Point> for &Point {
            type Output = Point;
            #[inline]
            fn $op_func(self, rhs: Point) -> Self::Output {
                Point::new(self.x $op rhs.x, self.y $op rhs.y)
            }
        }

        impl<'a, 'b> ops::$op_trait<&'b Point> for &'a Point {
            type Output = Point;
            #[inline]
            fn $op_func(self, _rhs: &'b Point) -> Self::Output {
                Point::new(self.x $op _rhs.x, self.y $op _rhs.y)
            }
        }

    };
}

ImplBinaryOp!(Add, add, +);
ImplBinaryOp!(Sub, sub, -);

/// Implements negation of a point.
impl Neg for Point {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        Self {
            x: -self.x,
            y: -self.y,
        }
    }
}

/// Implements multiplication of a point by a scalar.
impl Mul<f64> for Point {
    type Output = Self;
    #[inline]
    fn mul(self, num: f64) -> Self::Output {
        Self {
            x: self.x * num,
            y: self.y * num,
        }
    }
}

/// Implements division of a point by a scalar.
impl Div<f64> for Point {
    type Output = Self;
    #[inline]
    fn div(self, num: f64) -> Self::Output {
        Self {
            x: self.x / num,
            y: self.y / num,
        }
    }
}

impl Point {
    /// Computes the dot product of this point with another point.
    ///
    /// Uses improved precision via the Kahan summation method.
    ///
    /// # Arguments
    ///
    /// * `other` - The other point
    ///
    /// # Returns
    ///
    /// The dot product as a f64
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p1 = point(3.0, 4.0);
    /// let p2 = point(1.0, 2.0);
    /// let dot = p1.dot(p2); // 3*1 + 4*2 = 11.0
    /// ```
    #[inline]
    pub fn dot(&self, other: Self) -> f64 {
        sum_of_prod(self.x, other.x, self.y, other.y)
    }

    // #[inline]
    // pub fn perp(&self, other: Self) -> f64 {
    //     self.x * other.y - self.y * other.x
    // }

    /// Computes the perp product (cross product) of this point with another point.
    ///
    /// # Arguments
    ///
    /// * `other` - The other point
    ///
    /// # Returns
    ///
    /// The perp product as a f64
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p1 = point(3.0, 4.0);
    /// let p2 = point(1.0, 2.0);
    /// let perp = p1.perp(p2); // 3*2 - 4*1 = 2.0
    /// ```
    #[inline]
    pub fn perp(&self, other: Self) -> f64 {
        diff_of_prod(self.x, other.y, self.y, other.x)
    }

    /// Computes the Euclidean norm (magnitude) of this point when treated as a vector.
    ///
    /// # Returns
    ///
    /// The magnitude as a f64
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p = point(3.0, 4.0);
    /// let magnitude = p.norm(); // sqrt(3² + 4²) = 5.0
    /// ```
    #[inline]
    #[must_use]
    pub fn norm(&self) -> f64 {
        (self.dot(*self)).sqrt()
    }

    /// Normalizes this point to unit length and returns both the normalized point and original magnitude.
    ///
    /// The function uses robust computation to handle edge cases with very small or zero vectors.
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// * The normalized point (unit vector)
    /// * The original magnitude
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p = point(3.0, 4.0);
    /// let (normalized, magnitude) = p.normalize(false);
    /// // normalized will be approximately (0.6, 0.8)
    /// // magnitude will be 5.0
    /// ```
    #[inline]
    #[must_use]
    pub fn normalize(&self, robust: bool) -> (Point, f64) {
        if robust {
            let mut max_abs_comp = self.x.abs();
            let abs_comp = self.y.abs();
            if abs_comp > max_abs_comp {
                max_abs_comp = abs_comp;
            }

            let mut v = *self;
            if max_abs_comp > ZERO {
                v = v / max_abs_comp;
                let mut norm = v.norm();
                // Guard: prevent division by near-zero norm after scaling
                if norm > ZERO {
                    v = v / norm;
                    norm *= max_abs_comp;
                    (v, norm)
                } else {
                    // Scaled vector still has near-zero norm, return as-is
                    (v, ZERO)
                }
            } else {
                (point(ZERO, ZERO), ZERO)
            }
        } else {
            let norm = self.norm();
            let normalized = if norm > 0f64 {
                point(self.x / norm, self.y / norm)
            } else {
                point(ZERO, ZERO)
            };
            (normalized, norm)
        }
    }

    /// Checks if this point is almost equal to another point within a given ULP tolerance.
    ///
    /// Uses ULP (Units in the Last Place) comparison for floating point equality.
    ///
    /// # Arguments
    ///
    /// * `other` - The other point to compare with
    /// * `ulp` - The ULP tolerance for comparison
    ///
    /// # Returns
    ///
    /// True if the points are almost equal within the tolerance
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p1 = point(1.0, 2.0);
    /// let p2 = point(1.0000001, 2.0000001);
    /// let almost_equal = p1.almost_eq(p2, 10);
    /// ```
    /// Almost equal comparison with another Point using `ulp` given.
    #[inline]
    #[must_use]
    pub fn almost_eq(&self, other: Self, ulp: u64) -> bool {
        almost_equal_as_int(self.x, other.x, ulp) && almost_equal_as_int(self.y, other.y, ulp)
    }

    /// Checks if this point is close enough to another point within an epsilon tolerance.
    ///
    /// # Arguments
    ///
    /// * `other` - The other point to compare with  
    /// * `eps` - The epsilon tolerance for comparison
    ///
    /// # Returns
    ///
    /// True if the points are within epsilon distance in both x and y coordinates
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let p1 = point(1.0, 2.0);
    /// let p2 = point(1.001, 2.001);
    /// let close = p1.close_enough(p2, 0.01);
    /// ```
    #[inline]
    pub fn close_enough(&self, other: Self, eps: f64) -> bool {
        (self.x - other.x).abs() <= eps && (self.y - other.y).abs() <= eps
    }

    /// Computes the Manhattan distance to another point.
    fn manhattan(&self, other: Self) -> f64 {
        (self.x - other.x).abs() + (self.y - other.y).abs()
    }

    // /// diff_of_prod for points
    // #[inline]
    // pub fn diff_of_prod(&self, a: f64, other: Point, b: f64) -> Point {
    //     Point {
    //         x: diff_of_prod(self.x, a, other.x, b),
    //         y: diff_of_prod(self.y, a, other.y, b),
    //     }
    // }

    // /// sum_of_prod for points
    // #[inline]
    // pub fn sum_of_prod(&self, a: f64, other: Point, b: f64) -> Point {
    //     Point {
    //         x: sum_of_prod(self.x, a, other.x, b),
    //         y: sum_of_prod(self.y, a, other.y, b),
    //     }
    // }

    /// Linearly interpolate between two points.
    #[inline]
    #[must_use]
    pub fn lerp(self, other: Point, t: f64) -> Point {
        self + (other - self) * t
    }

    /// Sorts four collinear points.
    ///
    /// This function sorts four points that are expected to be collinear,
    /// and are usually a result of intersection of two collinear segments overlapping.
    ///
    /// Sort using sort networks.
    /// Ascending or descending order is not important.
    #[must_use]
    pub fn sort_colinear_points(
        a: Point,
        b: Point,
        c: Point,
        d: Point,
    ) -> (Point, Point, Point, Point) {
        let p0 = Coord { x: a.x, y: a.y };
        let p1 = Coord { x: b.x, y: b.y };
        let p2 = Coord { x: c.x, y: c.y };
        let p3 = Coord { x: d.x, y: d.y };
        let mut tt = (p0, p1, p2, p3);
        let diff0 = a - b;
        let diff1 = c - d;
        // create perpendicular segment to order points
        let perp = if diff0.dot(diff0).abs() >= diff1.dot(diff1).abs() {
            point(diff0.y, -diff0.x)
        } else {
            point(diff1.y, -diff1.x)
        };
        let t0 = Coord {
            x: perp.x,
            y: perp.y,
        };
        if orient2d(t0, tt.1, tt.3) < 0.0 {
            tt = (tt.0, tt.3, tt.2, tt.1);
        }
        if orient2d(t0, tt.0, tt.2) < 0.0 {
            tt = (tt.2, tt.1, tt.0, tt.3);
        }
        if orient2d(t0, tt.0, tt.1) < 0.0 {
            tt = (tt.1, tt.0, tt.2, tt.3);
        }
        if orient2d(t0, tt.2, tt.3) < 0.0 {
            tt = (tt.0, tt.1, tt.3, tt.2);
        }
        if orient2d(t0, tt.1, tt.2) < 0.0 {
            tt = (tt.0, tt.2, tt.1, tt.3);
        }
        let e = point(tt.0.x, tt.0.y);
        let f = point(tt.1.x, tt.1.y);
        let g = point(tt.2.x, tt.2.y);
        let h = point(tt.3.x, tt.3.y);
        (e, f, g, h)
    }
}

#[cfg(test)]
mod test_binary_op {
    use super::*;

    macro_rules! test_binary_op {
        ($v1:ident, $v2:ident, $op:tt, $expected:expr) => {
            assert!(($v1 $op $v2).almost_eq($expected, 10));
            assert!((&$v1 $op $v2).almost_eq($expected, 10));
            assert!(($v1 $op &$v2).almost_eq($expected, 10));
            assert!((&$v1 $op &$v2).almost_eq($expected, 10));
        };
    }

    macro_rules! test_num_op {
        ($v1:ident, $v2:ident, $op:tt, $expected:expr) => {
            assert!(($v1 $op $v2).almost_eq($expected, 10));
        };
    }

    #[test]
    fn test_ops() {
        let v1 = point(5.0, 5.0);
        let v2 = point(1.0, 2.0);
        let s = 2.0f64;
        test_binary_op!(v1, v2, +, point(6.0, 7.0));
        test_binary_op!(v1, v2, -, point(4.0, 3.0));
        test_num_op!(v1, s, *, point(10.0, 10.0));
        test_num_op!(v2, s, /, point(0.5, 1.0));
    }

    #[test]
    fn test_neg() {
        let p1 = point(1.0, 3.0);
        let p2 = point(-1.0, -3.0);
        assert_eq!(-p1, p2);
    }
}

#[cfg(test)]
mod test_point {
    use super::*;
    use crate::point::point;

    #[test]
    fn test_new() {
        let point0 = Point::new(1.0, 2.0);
        let point1 = point(1.0, 2.0);
        assert_eq!(point0, point1);
    }

    #[test]
    fn test_norm() {
        let p = point(1.0, 1.0);
        let e = p.norm();
        assert_eq!(e, 1.4142135623730951);
    }

    #[test]
    fn test_display() {
        let p = point(1.0, 2.0);
        //print!("{}", p);
        assert_eq!(
            "[1.00000000000000000000, 2.00000000000000000000]",
            format!("{}", p)
        );
    }

    #[test]
    fn test_sort_parallel_points_01() {
        let a = point(1.0, 1.0);
        let b = point(3.0, 3.0);
        let c = point(2.0, 2.0);
        let d = point(4.0, 4.0);
        let (e, f, g, h) = Point::sort_colinear_points(a, b, c, d);
        assert_eq!(e, a);
        assert_eq!(f, c);
        assert_eq!(g, b);
        assert_eq!(h, d);
    }

    #[test]
    fn test_sort_parallel_points_02() {
        let a = point(1.0, 1.0);
        let b = point(3.0, 3.0);
        let c = point(4.0, 4.0);
        let d = point(2.0, 2.0);
        let (e, f, g, h) = Point::sort_colinear_points(a, b, c, d);
        assert_eq!(e, a);
        assert_eq!(f, d);
        assert_eq!(g, b);
        assert_eq!(h, c);
    }

    #[test]
    fn test_sort_parallel_points_03() {
        let a = point(1.0, 1.0);
        let b = point(2.0, 2.0);
        let c = point(4.0, 4.0);
        let d = point(-1.0, -1.0);
        let (e, f, g, h) = Point::sort_colinear_points(a, b, c, d);
        assert_eq!(e, c);
        assert_eq!(f, b);
        assert_eq!(g, a);
        assert_eq!(h, d);
    }

    #[test]
    fn test_dot_product() {
        // Basic dot product
        let p1 = point(3.0, 4.0);
        let p2 = point(1.0, 2.0);
        assert_eq!(p1.dot(p2), 11.0); // 3*1 + 4*2 = 11

        // Orthogonal vectors (dot product should be 0)
        let p3 = point(1.0, 0.0);
        let p4 = point(0.0, 1.0);
        assert_eq!(p3.dot(p4), 0.0);

        // Dot product with self (magnitude squared)
        let p5 = point(3.0, 4.0);
        assert_eq!(p5.dot(p5), 25.0); // 3² + 4² = 25

        // Zero vector
        let zero = point(0.0, 0.0);
        let p6 = point(5.0, 7.0);
        assert_eq!(zero.dot(p6), 0.0);
        assert_eq!(p6.dot(zero), 0.0);

        // Negative values
        let p7 = point(-2.0, 3.0);
        let p8 = point(4.0, -1.0);
        assert_eq!(p7.dot(p8), -11.0); // -2*4 + 3*(-1) = -8 - 3 = -11
    }

    #[test]
    fn test_perp_product() {
        // Basic perpendicular product (cross product in 2D)
        let p1 = point(3.0, 4.0);
        let p2 = point(1.0, 2.0);
        assert_eq!(p1.perp(p2), 2.0); // 3*2 - 4*1 = 6 - 4 = 2

        // Parallel vectors (perp product should be 0)
        let p3 = point(2.0, 4.0);
        let p4 = point(1.0, 2.0);
        assert_eq!(p3.perp(p4), 0.0);

        // Anti-parallel vectors
        let p5 = point(1.0, 2.0);
        let p6 = point(-2.0, -4.0);
        assert_eq!(p5.perp(p6), 0.0);

        // Perpendicular vectors
        let p7 = point(1.0, 0.0);
        let p8 = point(0.0, 1.0);
        assert_eq!(p7.perp(p8), 1.0);
        assert_eq!(p8.perp(p7), -1.0);

        // Zero vector
        let zero = point(0.0, 0.0);
        let p9 = point(5.0, 7.0);
        assert_eq!(zero.perp(p9), 0.0);
        assert_eq!(p9.perp(zero), 0.0);
    }

    #[test]
    fn test_norm_magnitude() {
        // Basic magnitude calculation
        let p1 = point(3.0, 4.0);
        assert_eq!(p1.norm(), 5.0); // sqrt(3² + 4²) = 5

        // Unit vectors
        let unit_x = point(1.0, 0.0);
        let unit_y = point(0.0, 1.0);
        assert_eq!(unit_x.norm(), 1.0);
        assert_eq!(unit_y.norm(), 1.0);

        // Zero vector
        let zero = point(0.0, 0.0);
        assert_eq!(zero.norm(), 0.0);

        // Negative coordinates
        let p2 = point(-3.0, -4.0);
        assert_eq!(p2.norm(), 5.0);

        // Mixed sign coordinates
        let p3 = point(-3.0, 4.0);
        let p4 = point(3.0, -4.0);
        assert_eq!(p3.norm(), 5.0);
        assert_eq!(p4.norm(), 5.0);

        // Very small values
        let tiny = point(1e-10, 1e-10);
        assert!((tiny.norm() - std::f64::consts::SQRT_2 * 1e-10).abs() < 1e-15);

        // Very large values
        let large = point(1e10, 1e10);
        assert!((large.norm() - std::f64::consts::SQRT_2 * 1e10).abs() < 1e5);
    }

    #[test]
    fn test_normalize() {
        // Basic normalization
        let p1 = point(3.0, 4.0);
        let (normalized, magnitude) = p1.normalize(false);
        assert_eq!(magnitude, 5.0);
        assert!((normalized.norm() - 1.0).abs() < 1e-15);
        assert!((normalized.x - 0.6).abs() < 1e-15);
        assert!((normalized.y - 0.8).abs() < 1e-15);

        // Unit vector should remain unit
        let unit = point(1.0, 0.0);
        let (norm_unit, mag) = unit.normalize(false);
        assert_eq!(mag, 1.0);
        assert_eq!(norm_unit, unit);

        // Zero vector edge case
        let zero = point(0.0, 0.0);
        let (norm_zero, mag_zero) = zero.normalize(false);
        assert_eq!(mag_zero, 0.0);
        // Normalized zero should be zero (implementation detail)
        assert!(norm_zero.x.is_finite());
        assert!(norm_zero.y.is_finite());

        // Very small vector
        let tiny = point(1e-100, 1e-100);
        let (norm_tiny, mag_tiny) = tiny.normalize(false);
        assert!((mag_tiny - std::f64::consts::SQRT_2 * 1e-100).abs() < 1e-115);
        assert!((norm_tiny.norm() - 1.0).abs() < 1e-10); // May have some numerical error

        // Negative values
        let p2 = point(-6.0, -8.0);
        let (norm_p2, mag_p2) = p2.normalize(false);
        assert_eq!(mag_p2, 10.0);
        assert!((norm_p2.x - (-0.6)).abs() < 1e-15);
        assert!((norm_p2.y - (-0.8)).abs() < 1e-15);
    }

    #[test]
    fn test_almost_eq() {
        // Exactly equal points
        let p1 = point(1.0, 2.0);
        let p2 = point(1.0, 2.0);
        assert!(p1.almost_eq(p2, 0));

        // Very close points (should need some ULP tolerance)
        let p3 = point(1.0, 2.0);
        let p4 = point(1.0 + f64::EPSILON, 2.0 + f64::EPSILON); // Much smaller difference
        assert!(p3.almost_eq(p4, 1)); // 1 ULP should be enough for EPSILON difference

        // Different points
        let p5 = point(1.0, 2.0);
        let p6 = point(1.1, 2.1);
        assert!(!p5.almost_eq(p6, 10));

        // Zero points
        let zero1 = point(0.0, 0.0);
        let zero2 = point(0.0, 0.0);
        assert!(zero1.almost_eq(zero2, 0));

        // Negative zero vs positive zero
        let neg_zero = point(-0.0, -0.0);
        let pos_zero = point(0.0, 0.0);
        assert!(neg_zero.almost_eq(pos_zero, 0));

        // Large values with minimal difference
        let big1 = point(1e10, 1e10);
        let big2 = point(1e10 * (1.0 + f64::EPSILON), 1e10 * (1.0 + f64::EPSILON));
        assert!(big1.almost_eq(big2, 100)); // ULP tolerance needed for large values

        // One coordinate different by EPSILON
        let p7 = point(1.0, 2.0);
        let p8 = point(1.0 + f64::EPSILON, 2.0);
        assert!(p7.almost_eq(p8, 1));

        let p9 = point(1.0, 2.0);
        let p10 = point(1.0, 2.0 + f64::EPSILON);
        assert!(p9.almost_eq(p10, 1));

        // Test different signs - should only be equal if both are zero
        let pos = point(1.0, 1.0);
        let neg = point(-1.0, -1.0);
        assert!(!pos.almost_eq(neg, 1000));
    }

    #[test]
    fn test_close_enough() {
        // Exactly equal points
        let p1 = point(1.0, 2.0);
        let p2 = point(1.0, 2.0);
        assert!(p1.close_enough(p2, 0.0));

        // Points within epsilon (both coordinates must be within epsilon)
        let p3 = point(1.0, 2.0);
        let p4 = point(1.005, 2.005); // Both coordinates are 0.005 different
        assert!(p3.close_enough(p4, 0.006)); // eps > 0.005
        assert!(!p3.close_enough(p4, 0.004)); // eps < 0.005

        // Points outside epsilon
        let p5 = point(1.0, 2.0);
        let p6 = point(1.1, 2.1); // Both coordinates are 0.1 different
        assert!(!p5.close_enough(p6, 0.05));
        assert!(p5.close_enough(p6, 0.15));

        // Zero tolerance - requires exact equality
        let p7 = point(1.0, 2.0);
        let p8 = point(1.0, 2.0);
        assert!(p7.close_enough(p8, f64::EPSILON)); // Use smallest epsilon instead of 0.0

        let p9 = point(1.0, 2.0);
        let p10 = point(1.001, 2.001);
        assert!(!p9.close_enough(p10, 0.0));

        // Negative coordinates
        let p11 = point(-1.0, -2.0);
        let p12 = point(-1.005, -2.005);
        assert!(p11.close_enough(p12, 0.01));

        // Mixed signs
        let p13 = point(1.0, -2.0);
        let p14 = point(1.005, -2.005);
        assert!(p13.close_enough(p14, 0.01));

        // Large epsilon
        let p15 = point(0.0, 0.0);
        let p16 = point(5.0, 5.0);
        assert!(p15.close_enough(p16, 10.0));

        // One coordinate within, one outside - should fail
        let p17 = point(1.0, 2.0);
        let p18 = point(1.005, 2.05); // x within 0.01, y outside 0.01
        assert!(!p17.close_enough(p18, 0.01));

        // Boundary case - exactly at epsilon
        let p19 = point(1.0, 2.0);
        let p20 = point(1.01, 2.01); // exactly 0.01 difference
        assert!(!p19.close_enough(p20, 0.01)); // < epsilon, not <= epsilon
        assert!(p19.close_enough(p20, 0.011)); // > epsilon
    }

    // #[test]
    // fn test_diff_of_prod() {
    //     let p1 = point(2.0, 3.0);
    //     let p2 = point(4.0, 5.0);
    //     let a = 2.0;
    //     let b = 3.0;

    //     let result = p1.diff_of_prod(a, p2, b);
    //     // Expected: Point(p1.x * a - p2.x * b, p1.y * a - p2.y * b)
    //     // = Point(2.0 * 2.0 - 4.0 * 3.0, 3.0 * 2.0 - 5.0 * 3.0)
    //     // = Point(4.0 - 12.0, 6.0 - 15.0)
    //     // = Point(-8.0, -9.0)
    //     assert_eq!(result, point(-8.0, -9.0));

    //     // Test with zero
    //     let zero = point(0.0, 0.0);
    //     let p3 = point(1.0, 1.0);
    //     let result_zero = zero.diff_of_prod(1.0, p3, 1.0);
    //     assert_eq!(result_zero, point(-1.0, -1.0));

    //     // Test with identity
    //     let p4 = point(5.0, 7.0);
    //     let result_identity = p4.diff_of_prod(1.0, zero, 0.0);
    //     assert_eq!(result_identity, p4);
    // }

    // #[test]
    // fn test_sum_of_prod() {
    //     let p1 = point(2.0, 3.0);
    //     let p2 = point(4.0, 5.0);
    //     let a = 2.0;
    //     let b = 3.0;

    //     let result = p1.sum_of_prod(a, p2, b);
    //     // Expected: Point(p1.x * a + p2.x * b, p1.y * a + p2.y * b)
    //     // = Point(2.0 * 2.0 + 4.0 * 3.0, 3.0 * 2.0 + 5.0 * 3.0)
    //     // = Point(4.0 + 12.0, 6.0 + 15.0)
    //     // = Point(16.0, 21.0)
    //     assert_eq!(result, point(16.0, 21.0));

    //     // Test with zero
    //     let zero = point(0.0, 0.0);
    //     let p3 = point(1.0, 1.0);
    //     let result_zero = zero.sum_of_prod(1.0, p3, 1.0);
    //     assert_eq!(result_zero, point(1.0, 1.0));

    //     // Test with identity
    //     let p4 = point(5.0, 7.0);
    //     let result_identity = p4.sum_of_prod(1.0, zero, 0.0);
    //     assert_eq!(result_identity, p4);

    //     // Test weighted average-like operation
    //     let p5 = point(0.0, 0.0);
    //     let p6 = point(10.0, 20.0);
    //     let result_weighted = p5.sum_of_prod(0.3, p6, 0.7);
    //     assert_eq!(result_weighted, point(7.0, 14.0));
    // }

    #[test]
    fn test_lerp() {
        // Basic interpolation
        let p1 = point(0.0, 0.0);
        let p2 = point(10.0, 20.0);

        // At t=0, should return p1
        assert_eq!(p1.lerp(p2, 0.0), p1);

        // At t=1, should return p2
        assert_eq!(p1.lerp(p2, 1.0), p2);

        // At t=0.5, should return midpoint
        assert_eq!(p1.lerp(p2, 0.5), point(5.0, 10.0));

        // At t=0.25
        assert_eq!(p1.lerp(p2, 0.25), point(2.5, 5.0));

        // At t=0.75
        assert_eq!(p1.lerp(p2, 0.75), point(7.5, 15.0));

        // Extrapolation (t < 0)
        assert_eq!(p1.lerp(p2, -0.5), point(-5.0, -10.0));

        // Extrapolation (t > 1)
        assert_eq!(p1.lerp(p2, 1.5), point(15.0, 30.0));

        // Same points
        let p3 = point(5.0, 5.0);
        assert_eq!(p3.lerp(p3, 0.7), p3);

        // Negative coordinates
        let p4 = point(-5.0, -10.0);
        let p5 = point(5.0, 10.0);
        assert_eq!(p4.lerp(p5, 0.5), point(0.0, 0.0));
    }

    #[test]
    fn test_default() {
        let default_point = Point::default();
        assert_eq!(default_point, point(0.0, 0.0));
    }

    #[test]
    fn test_clone_copy() {
        let p1 = point(3.0, 4.0);
        let p2 = p1; // Copy
        let p3 = p1.clone(); // Clone

        assert_eq!(p1, p2);
        assert_eq!(p1, p3);
        assert_eq!(p2, p3);
    }

    #[test]
    fn test_partial_ord() {
        let p1 = point(1.0, 1.0);
        let p2 = point(2.0, 2.0);
        let p3 = point(1.0, 2.0);

        // Note: PartialOrd for Point compares lexicographically (x first, then y)
        assert!(p1 < p2);
        assert!(p1 < p3);
        assert!(p3 < p2);

        let p4 = point(1.0, 1.0);
        assert!(p1 <= p4);
        assert!(p1 >= p4);

        // Same x, different y
        let p5 = point(1.0, 0.5);
        let p6 = point(1.0, 1.5);
        assert!(p5 < p6);
    }

    #[test]
    fn test_division_by_scalar() {
        let p1 = point(10.0, 20.0);
        let result = p1 / 2.0;
        assert_eq!(result, point(5.0, 10.0));

        // Division by 1
        let p2 = point(7.0, 14.0);
        assert_eq!(p2 / 1.0, p2);

        // Division by negative
        let p3 = point(6.0, 8.0);
        assert_eq!(p3 / -2.0, point(-3.0, -4.0));

        // Division of zero vector
        let zero = point(0.0, 0.0);
        assert_eq!(zero / 5.0, zero);
    }

    #[test]
    fn test_edge_cases() {
        // Test with infinity
        let inf_point = point(f64::INFINITY, f64::NEG_INFINITY);
        assert!(inf_point.x.is_infinite());
        assert!(inf_point.y.is_infinite());

        // Test with NaN
        let nan_point = point(f64::NAN, 1.0);
        assert!(nan_point.x.is_nan());
        assert!(nan_point.y.is_finite());

        // Operations with NaN should produce NaN
        let normal_point = point(1.0, 2.0);
        let result = normal_point + nan_point;
        assert!(result.x.is_nan());
        assert!(result.y.is_finite());

        // Very large numbers
        let large1 = point(f64::MAX / 2.0, f64::MAX / 2.0);
        let large2 = point(f64::MAX / 2.0, f64::MAX / 2.0);
        // This might overflow, but should handle gracefully
        let _sum = large1 + large2;

        // Very small numbers
        let tiny1 = point(f64::MIN_POSITIVE, f64::MIN_POSITIVE);
        let tiny2 = point(f64::MIN_POSITIVE, f64::MIN_POSITIVE);
        let sum_tiny = tiny1 + tiny2;
        assert!(sum_tiny.x > 0.0);
        assert!(sum_tiny.y > 0.0);
    }

    #[test]
    fn test_display_formatting() {
        // Test various number formats
        let p1 = point(1.0, 2.0);
        let display1 = format!("{}", p1);
        assert_eq!(display1, "[1.00000000000000000000, 2.00000000000000000000]");

        // Test with decimal places
        let p2 = point(1.5, 2.7);
        let display2 = format!("{}", p2);
        assert!(display2.contains("1.5"));
        assert!(display2.contains("2.7"));

        // Test with negative numbers
        let p3 = point(-1.5, -2.7);
        let display3 = format!("{}", p3);
        assert!(display3.contains("-1.5"));
        assert!(display3.contains("-2.7"));

        // Test with zero
        let zero = point(0.0, 0.0);
        let display_zero = format!("{}", zero);
        assert!(display_zero.contains("0.00000000000000000000"));
    }

    #[test]
    fn test_points_order() {
        // Test with simple horizontal line - this pattern works reliably
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let p_above = point(1.0, 1.0); // Above line, positive orientation
        let p_below = point(1.0, -1.0); // Below line, negative orientation

        assert!(points_order(a, b, p_above) > 0.0);
        assert!(points_order(a, b, p_below) < 0.0);

        // Test with 3 points on unit circle (all points by construction lie on same circle)
        let radius = 1.0;
        let a_circle = point(radius, 0.0); // (1, 0)
        let b_circle = point(0.0, radius); // (0, 1)
        let p_circle = point(-radius, 0.0); // (-1, 0)

        // This gives a specific orientation value for these circle points
        let circle_result = points_order(a_circle, b_circle, p_circle);
        assert!(circle_result.is_finite());
        assert!(circle_result > 0.0); // Based on our testing, this is positive
    }

    #[test]
    fn test_points_order_comprehensive() {
        // Test with larger scale using reliable horizontal line pattern
        let a = point(0.0, 0.0);
        let b = point(10.0, 0.0);
        let p_above = point(5.0, 3.0); // Above line, positive orientation
        let p_below = point(5.0, -3.0); // Below line, negative orientation

        let result_above = points_order(a, b, p_above);
        let result_below = points_order(a, b, p_below);

        assert!(result_above > 0.0);
        assert!(result_below < 0.0);

        // Test with 3 points on larger circle (all on same circle by construction)
        let radius = 5.0;
        let center_x = 0.0;
        let center_y = 0.0;

        // Points at specific angles on circle
        let angle_a = 0.0f64; //        let angle_b = std::f64::consts::PI / 3.0; // 60°
        let angle_p = 2.0 * std::f64::consts::PI / 3.0; // 120°

        let a_circle = point(
            center_x + radius * angle_a.cos(),
            center_y + radius * angle_a.sin(),
        );
        let b_circle = point(
            center_x + radius * angle_b.cos(),
            center_y + radius * angle_b.sin(),
        );
        let p_circle = point(
            center_x + radius * angle_p.cos(),
            center_y + radius * angle_p.sin(),
        );

        let circle_result = points_order(a_circle, b_circle, p_circle);
        assert!(circle_result.is_finite());

        // Test order independence - swapping a and b should negate result
        let result_forward = points_order(a, b, p_above);
        let result_backward = points_order(b, a, p_above);
        assert!((result_forward + result_backward).abs() < 1e-10);
    }

    #[test]
    fn test_points_order_edge_cases() {
        // Test with very small circle using sin/cos
        let tiny_radius = 1e-6;
        let tiny_a = point(tiny_radius * 0.0f64.cos(), tiny_radius * 0.0f64.sin()); //        let tiny_b = point(
            tiny_radius * (std::f64::consts::PI / 2.0).cos(),
            tiny_radius * (std::f64::consts::PI / 2.0).sin(),
        ); // 90°
        let tiny_p = point(
            tiny_radius * std::f64::consts::PI.cos(),
            tiny_radius * std::f64::consts::PI.sin(),
        ); // 180°

        let tiny_result = points_order(tiny_a, tiny_b, tiny_p);
        assert!(tiny_result.is_finite());
        assert!(tiny_result > 0.0);

        // Test with large circle using sin/cos
        let large_radius = 1e6;
        let large_a = point(large_radius * 0.0f64.cos(), large_radius * 0.0f64.sin()); //        let large_b = point(
            large_radius * (std::f64::consts::PI / 2.0).cos(),
            large_radius * (std::f64::consts::PI / 2.0).sin(),
        ); // 90°
        let large_p = point(
            large_radius * std::f64::consts::PI.cos(),
            large_radius * std::f64::consts::PI.sin(),
        ); // 180°

        let large_result = points_order(large_a, large_b, large_p);
        assert!(large_result > 0.0);

        // Test with identical points (degenerate case)
        let same_point = point(1.0, 1.0);
        let degenerate_result = points_order(same_point, same_point, same_point);
        assert_eq!(degenerate_result, 0.0);

        // Test with points very close together on unit circle
        let angle1 = 0.0f64;
        let angle2 = 1e-6f64; // Very small angle difference
        let angle3 = std::f64::consts::PI; // Opposite side

        let close_a = point(angle1.cos(), angle1.sin());
        let close_b = point(angle2.cos(), angle2.sin());
        let close_p = point(angle3.cos(), angle3.sin());

        let close_result = points_order(close_a, close_b, close_p);
        assert!(close_result.is_finite());
        assert!(close_result.abs() > 0.0);
    }
}

#[cfg(test)]
mod test_normalize {
    use crate::point::point;
    #[test]
    fn test_normalize_robust_vs_simple() {
        // Test cases where robust and simple implementations differ significantly

        // Case 1: Very small vectors - simple implementation may underflow
        let tiny_vector = point(1e-200, 1e-200);
        let (simple_norm, simple_mag) = tiny_vector.normalize(false);
        let (robust_norm, robust_mag) = tiny_vector.normalize(true);

        println!("Tiny vector test:");
        println!("  Simple: norm={}, mag={:.2e}", simple_norm, simple_mag);
        println!("  Robust: norm={}, mag={:.2e}", robust_norm, robust_mag);

        // Simple implementation likely underflows to zero
        // Robust should maintain proper normalization
        assert!(robust_mag > 0.0, "Robust should handle tiny vectors");
        if simple_mag == 0.0 {
            // Simple underflowed - robust should be better
            assert!(
                (robust_norm.norm() - 1.0).abs() < 1e-10,
                "Robust should produce unit vector"
            );
        }

        // Case 2: Very large vectors - simple implementation may overflow
        let large_vector = point(1e150, 1e150);
        let (simple_norm_large, simple_mag_large) = large_vector.normalize(false);
        let (robust_norm_large, robust_mag_large) = large_vector.normalize(true);

        println!("Large vector test:");
        println!(
            "  Simple: norm={}, mag={:.2e}",
            simple_norm_large, simple_mag_large
        );
        println!(
            "  Robust: norm={}, mag={:.2e}",
            robust_norm_large, robust_mag_large
        );

        // Robust should handle large vectors better
        assert!(
            robust_mag_large.is_finite(),
            "Robust magnitude should be finite"
        );
        assert!(
            (robust_norm_large.norm() - 1.0).abs() < 1e-10,
            "Robust should produce unit vector"
        );

        // Case 3: Mixed scale vectors
        let mixed_vector = point(1e-100, 1e100);
        let (simple_norm_mixed, simple_mag_mixed) = mixed_vector.normalize(false);
        let (robust_norm_mixed, robust_mag_mixed) = mixed_vector.normalize(true);

        println!("Mixed scale vector test:");
        println!(
            "  Simple: norm={}, mag={:.2e}",
            simple_norm_mixed, simple_mag_mixed
        );
        println!(
            "  Robust: norm={}, mag={:.2e}",
            robust_norm_mixed, robust_mag_mixed
        );

        // Both should handle this case, but robust may be more precise
        assert!(simple_mag_mixed.is_finite() && robust_mag_mixed.is_finite());

        // Case 4: Normal vectors - both should perform similarly
        let normal_vector = point(3.0, 4.0);
        let (simple_norm_normal, simple_mag_normal) = normal_vector.normalize(false);
        let (robust_norm_normal, robust_mag_normal) = normal_vector.normalize(true);

        // Both should give essentially the same result for normal vectors
        assert!((simple_mag_normal - robust_mag_normal).abs() < 1e-10);
        assert!((simple_norm_normal - robust_norm_normal).norm() < 1e-10);
        assert!((simple_norm_normal.norm() - 1.0).abs() < 1e-10);
        assert!((robust_norm_normal.norm() - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_normalize_edge_cases_robust_vs_simple() {
        // Test specific edge cases where numerical precision matters

        // Zero vector - both should handle the same way
        let zero_vector = point(0.0, 0.0);
        let (simple_zero, simple_mag_zero) = zero_vector.normalize(false);
        let (robust_zero, robust_mag_zero) = zero_vector.normalize(true);

        assert_eq!(simple_mag_zero, 0.0);
        assert_eq!(robust_mag_zero, 0.0);
        assert_eq!(simple_zero, point(0.0, 0.0));
        assert_eq!(robust_zero, point(0.0, 0.0));

        // Very small but non-zero vector
        let epsilon_vector = point(f64::EPSILON, f64::EPSILON);
        let (simple_eps, simple_mag_eps) = epsilon_vector.normalize(false);
        let (robust_eps, robust_mag_eps) = epsilon_vector.normalize(true);

        // Both should handle machine epsilon, but let's verify they're close
        if simple_mag_eps > 0.0 && robust_mag_eps > 0.0 {
            let mag_diff = (simple_mag_eps - robust_mag_eps).abs();
            let norm_diff = (simple_eps - robust_eps).norm();

            // Magnitudes should be very close
            assert!(
                mag_diff / simple_mag_eps < 1e-10,
                "Magnitude difference too large"
            );

            // Normalized vectors should be very close
            assert!(norm_diff < 1e-10, "Normalized vector difference too large");
        }

        // Single large component
        let single_large = point(1e100, 0.0);
        let (simple_single, simple_mag_single) = single_large.normalize(false);
        let (robust_single, robust_mag_single) = single_large.normalize(true);

        assert!(
            (simple_single.norm() - 1.0).abs() < 1e-10,
            "Simple should normalize correctly"
        );
        assert!(
            (robust_single.norm() - 1.0).abs() < 1e-10,
            "Robust should normalize correctly"
        );
        assert!(
            (simple_mag_single - robust_mag_single).abs() < 1e90,
            "Magnitudes should be close"
        );

        // Single tiny component
        let single_tiny = point(1e-200, 0.0);
        let (simple_tiny, simple_mag_tiny) = single_tiny.normalize(false);
        let (robust_tiny, robust_mag_tiny) = single_tiny.normalize(true);

        // Robust should handle this better than simple
        if simple_mag_tiny == 0.0 {
            // Simple underflowed
            assert!(robust_mag_tiny > 0.0, "Robust should not underflow");
            assert!(
                (robust_tiny - point(1.0, 0.0)).norm() < 1e-10,
                "Robust should give correct direction"
            );
        } else {
            // Both handled it - should be similar
            assert!((simple_mag_tiny - robust_mag_tiny).abs() / robust_mag_tiny < 1e-10);
            assert!(
                (simple_tiny - robust_tiny).norm() < 1e-10,
                "Normalized vectors should be close"
            );
        }
    }

    #[test]
    fn test_normalize_precision_comparison() {
        // Compare precision of both implementations across different scales

        let test_vectors = vec![
            ("Normal", point(3.0, 4.0)),
            ("Unit", point(1.0, 0.0)),
            ("Small", point(1e-10, 1e-10)),
            ("Large", point(1e10, 1e10)),
            ("Mixed small-large", point(1e-50, 1e50)),
            (
                "Near machine epsilon",
                point(f64::EPSILON * 10.0, f64::EPSILON * 10.0),
            ),
        ];

        for (name, vector) in test_vectors {
            let (simple_norm, simple_mag) = vector.normalize(false);
            let (robust_norm, robust_mag) = vector.normalize(true);

            // Check that both produce valid results when they don't underflow/overflow
            if simple_mag > 0.0 && simple_mag.is_finite() {
                let simple_unit_error = (simple_norm.norm() - 1.0).abs();
                assert!(
                    simple_unit_error < 1e-10,
                    "Simple implementation unit error too large for {}: {:.2e}",
                    name,
                    simple_unit_error
                );
            }

            if robust_mag > 0.0 && robust_mag.is_finite() {
                let robust_unit_error = (robust_norm.norm() - 1.0).abs();
                assert!(
                    robust_unit_error < 1e-10,
                    "Robust implementation unit error too large for {}: {:.2e}",
                    name,
                    robust_unit_error
                );
            }

            // When both produce valid results, they should be reasonably close
            if simple_mag > 0.0
                && robust_mag > 0.0
                && simple_mag.is_finite()
                && robust_mag.is_finite()
            {
                let mag_relative_error = (simple_mag - robust_mag).abs() / robust_mag;

                // Allow for some numerical differences, but they shouldn't be huge
                if mag_relative_error > 1e-6 {
                    println!(
                        "Warning: Large magnitude difference for {}: simple={:.2e}, robust={:.2e}, rel_error={:.2e}",
                        name, simple_mag, robust_mag, mag_relative_error
                    );
                }
            }
        }
    }

    #[test]
    fn test_normalize_underflow_demonstration() {
        // Demonstrate clear cases where simple implementation fails due to underflow

        println!("=== Underflow Demonstration ===");

        // Very tiny vector that causes underflow in simple implementation
        let tiny = point(1e-200, 0.0);
        let (simple_norm, simple_mag) = tiny.normalize(false);
        let (robust_norm, robust_mag) = tiny.normalize(true);

        println!("Tiny vector [1e-200, 0]:");
        println!(
            "  Simple: normalized={}, magnitude={:.2e}",
            simple_norm, simple_mag
        );
        println!(
            "  Robust: normalized={}, magnitude={:.2e}",
            robust_norm, robust_mag
        );

        // Simple should fail (underflow to zero)
        assert_eq!(
            simple_mag, 0.0,
            "Simple implementation should underflow to zero"
        );
        assert_eq!(
            simple_norm,
            point(0.0, 0.0),
            "Simple should return zero vector"
        );

        // Robust should succeed
        assert!(robust_mag > 0.0, "Robust should not underflow");
        assert!(
            (robust_norm - point(1.0, 0.0)).norm() < 1e-10,
            "Robust should give correct unit vector"
        );
        assert!(
            (robust_norm.norm() - 1.0).abs() < 1e-10,
            "Robust result should be unit length"
        );

        println!("✓ Robust implementation correctly handles underflow case");

        // Another case with both components tiny
        let tiny_both = point(1e-250, 1e-250);
        let (simple_both, simple_mag_both) = tiny_both.normalize(false);
        let (robust_both, robust_mag_both) = tiny_both.normalize(true);

        println!("\nTiny vector [1e-250, 1e-250]:");
        println!(
            "  Simple: normalized={}, magnitude={:.2e}",
            simple_both, simple_mag_both
        );
        println!(
            "  Robust: normalized={}, magnitude={:.2e}",
            robust_both, robust_mag_both
        );

        if simple_mag_both == 0.0 {
            println!("✓ Simple underflowed, but robust handled it correctly");
            assert!(robust_mag_both > 0.0);
            assert!((robust_both.norm() - 1.0).abs() < 1e-10);
        } else {
            println!("Both implementations handled this case");
        }
    }

    #[test]
    fn test_normalize_overflow_demonstration() {
        // Demonstrate cases where simple implementation may have precision issues with large numbers

        println!("=== Large Number Precision Test ===");

        // Very large vector
        let large = point(1e100, 1e100);
        let (simple_large, simple_mag_large) = large.normalize(false);
        let (robust_large, robust_mag_large) = large.normalize(true);

        println!("Large vector [1e100, 1e100]:");
        println!(
            "  Simple: normalized={}, magnitude={:.2e}",
            simple_large, simple_mag_large
        );
        println!(
            "  Robust: normalized={}, magnitude={:.2e}",
            robust_large, robust_mag_large
        );

        // Both should work, but robust may be more precise
        assert!(
            simple_mag_large.is_finite(),
            "Simple magnitude should be finite"
        );
        assert!(
            robust_mag_large.is_finite(),
            "Robust magnitude should be finite"
        );

        let simple_unit_error = (simple_large.norm() - 1.0).abs();
        let robust_unit_error = (robust_large.norm() - 1.0).abs();

        println!("  Simple unit length error: {:.2e}", simple_unit_error);
        println!("  Robust unit length error: {:.2e}", robust_unit_error);

        // Extremely large vector that might cause issues
        let extreme = point(1e200, 0.0);
        let (simple_extreme, simple_mag_extreme) = extreme.normalize(false);
        let (robust_extreme, robust_mag_extreme) = extreme.normalize(true);

        println!("\nExtreme vector [1e200, 0]:");
        println!(
            "  Simple: normalized={}, magnitude={:.2e}",
            simple_extreme, simple_mag_extreme
        );
        println!(
            "  Robust: normalized={}, magnitude={:.2e}",
            robust_extreme, robust_mag_extreme
        );

        // Check if simple implementation overflows
        if !simple_mag_extreme.is_finite() {
            println!("✓ Simple implementation overflowed, robust should handle it");
            assert!(robust_mag_extreme.is_finite(), "Robust should not overflow");
            assert!(
                (robust_extreme.norm() - 1.0).abs() < 1e-10,
                "Robust should produce unit vector"
            );
        } else {
            println!("Both implementations handled extreme case");
        }
    }
}