ekmett / linear

Low-dimensional linear algebra primitives for Haskell.
http://hackage.haskell.org/package/linear
Other
200 stars 50 forks source link

add frobenius norm? #151

Closed chessai closed 5 years ago

chessai commented 5 years ago
frobenius :: (Num a, Foldable f, Additive f, Additive g, Distributive g, Trace g) => f (g a) -> a
frobenius m = trace (transpose m !*! m)

I think this would be a useful definition to have in general.

For a sprinkle of motivation, in the code I'm currently working on I want to be able to approximately compare two matrices of floating point numbers. To do this, i'm saying that the frobenius norm of the difference of two matrices should be less than a given epsilon (just using Linear.Epsilon.Epsilon). In code:

epsEq :: (Fractional a, Epsilon a, Foldable f, Additive f, Additive g, Distributive g, Trace g) => f (g a) -> f (g a) -> Bool
epsEq m1 m2 = nearZero $ frobenius (m1 !-! m2)

EDIT: I know that can compound rounding errors, i'm just going to do the comparison element-wise (subtract elementwise and then call nearZero), but i still think a frobenius norm function might be useful

chessai commented 5 years ago

thanks!