File tree Expand file tree Collapse file tree 1 file changed +12
-24
lines changed
Expand file tree Collapse file tree 1 file changed +12
-24
lines changed Original file line number Diff line number Diff line change @@ -191,13 +191,9 @@ public function projection(self $other): self
191191 */
192192 public function l1Norm (): float
193193 {
194- $ sum = 0 ;
195-
196- foreach ($ this ->toArray () as $ value ) {
197- $ sum += abs ($ value );
198- }
199-
200- return $ sum ;
194+ return array_reduce ($ this ->toArray (), function (float $ carry , float $ value ) {
195+ return $ carry + abs ($ value );
196+ }, 0 );
201197 }
202198
203199 /**
@@ -214,32 +210,24 @@ public function l1Norm(): float
214210 */
215211 public function l2Norm (): float
216212 {
217- $ literal = [];
218-
219- for ($ i = 0 , $ rows = $ this ->getSize (); $ i < $ rows ; $ i ++) {
220- $ literal [] = $ this ->toArray ()[$ i ] ** 2 ;
221- }
222-
223- return sqrt (array_sum ($ literal ));
213+ return sqrt (array_reduce ($ this ->toArray (), function (float $ carry , float $ value ) {
214+ return $ carry + pow ($ value , 2 );
215+ }, 0 ));
224216 }
225217
226218 /**
227219 * Max norm (infinity norm) (|x|∞)
228220 *
229221 * |x|∞ = max |x|
230222 *
231- * @return number
223+ * @return float
232224 */
233- public function maxNorm ()
225+ public function maxNorm (): float
234226 {
235- $ max = abs ($ this ->toArray ()[0 ]);
236-
237- foreach ($ this ->toArray () as $ value ) {
238- if (abs ($ value ) > $ max ) {
239- $ max = abs ($ value );
240- }
241- }
227+ return array_reduce ($ this ->toArray (), function (float $ carry , float $ value ) {
228+ $ value = abs ($ value );
242229
243- return $ max ;
230+ return $ carry > $ value ? $ carry : $ value ;
231+ }, -INF );
244232 }
245233}
You can’t perform that action at this time.
0 commit comments