File tree Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -226,7 +226,7 @@ impl F32 {
226
226
/// Is this floating point value even?
227
227
fn is_even ( & self ) -> bool {
228
228
// any floating point value that doesn't fit in an i32 range is even,
229
- // and will loose 1's digit precision at exp values of 23+
229
+ // and will lose 1's digit precision at exp values of 23+
230
230
if self . extract_exponent_value ( ) >= 31 {
231
231
true
232
232
} else {
Original file line number Diff line number Diff line change 72
72
. sum :: < f32 > ( )
73
73
. sqrt ( )
74
74
}
75
+
76
+ /// Returns a normalized version of the vector.
77
+ fn normalized ( mut self ) -> Self
78
+ where
79
+ Self : FromIterator < C > ,
80
+ C : Into < f32 > + From < f32 > ,
81
+ {
82
+ let norm = self . magnitude ( ) ;
83
+ self . map ( |n| C :: from ( n. into ( ) / norm) )
84
+ }
85
+
86
+ /// Applies a function to each element of the vector
87
+ /// and returns a new vector of the transformed elements.
88
+ fn map < F > ( & mut self , map : F ) -> Self
89
+ where
90
+ F : FnMut ( C ) -> C ,
91
+ {
92
+ Self :: from_iter ( self . iter ( ) . map ( map) )
93
+ }
94
+ }
95
+
96
+ #[ cfg( test) ]
97
+ mod tests {
98
+ use super :: * ;
99
+
100
+ #[ test]
101
+ fn normalized ( ) {
102
+ const ERROR : f32 = 1e-6 ;
103
+ let vec = Vector3d {
104
+ x : 3.0 ,
105
+ y : 4.0 ,
106
+ z : 5.0 ,
107
+ } ;
108
+ let norm = vec. magnitude ( ) ;
109
+ assert ! ( ( norm - 7.071068 ) . abs( ) <= ERROR ) ;
110
+
111
+ let normalized = vec. normalized ( ) ;
112
+ assert ! ( ( normalized. x - 0.42426407 ) . abs( ) <= ERROR ) ;
113
+ assert ! ( ( normalized. y - 0.56568545 ) . abs( ) <= ERROR ) ;
114
+ assert ! ( ( normalized. z - 0.70710677 ) . abs( ) <= ERROR ) ;
115
+ }
75
116
}
You can’t perform that action at this time.
0 commit comments