WolframLang: Detect Zero Vector
What is the most efficient or elegant way to detect zero vector of n dimensions (list whose element are all 0)?
- solution 1, compute the sum of squares.
(Total[#^2] < 0.00000001 &)
- solution 2, compute the Norm.
(Norm[#] < 0.00000001 &)
analysis:
- Computing sum of squares in theory is less number of operation, but it requires 2 calls of function.
- Computing norm is 1 additional operation, namely the square root. But, just 1 call of a builtin function.
Computing the Norm wins. Almost twice as fast.
isZeroVector1 = Function[Total[#^2] < 0.00000001]; isZeroVector2 = Function[Norm[#] < 0.00000001]; data = Table[{RandomReal[], RandomReal[], RandomReal[]}, {900000}]; x1 = Timing[Map[isZeroVector1, data]]; x2 = Timing[Map[isZeroVector2, data]]; {First@x1, First@x2} (* {1.67188, 0.90625} *) SameQ @@ {Last@x1, Last@x2} (* True *)