Re: [eigen] Behavior of sum() and prod() for empty vectors

[ Thread Index | Date Index | More lists.tuxfamily.org/eigen Archives ]


Thanks a lot! I'm going to test my code with the Eigen devel branch next week.

Nice weekend for everyone!
Martin



Am Freitag 16 Juli 2010, 14:06:23 schrieb Gael Guennebaud:
> you are right, problem fixed for sum(), prod() and indirectly for
> trace() and dot().
> 
> I also made sure an assertion is triggered for other reductions (that
> was not the case).
> 
> cheers,
> 
> gael
> 
> On Fri, Jul 16, 2010 at 1:34 PM, Martin Senst <martin.senst@xxxxxx> wrote:
> > Dear developers,
> > 
> > I just stumbled upon a nasty issue with reductions of empty (zero-sized)
> > vectors. I'm currently using Eigen3 Beta 1.
> > Consider the following program:
> > 
> > 
> > #include <Eigen/Core>
> > #include <iostream>
> > 
> > int main()
> > {
> >  Eigen::VectorXd v = Eigen::VectorXd::Random(4);
> > 
> >  std::cout << v.head(0).sum() << std::endl; // outputs v(0)
> >  std::cout << v.tail(0).sum() << std::endl; // outputs 0
> >  std::cout << v.segment(2, 0).sum() << std::endl; // outputs v(2)
> > 
> >  Eigen::VectorXd w;
> >  std::cout << w.sum() << std::endl; // segfaults
> > }
> > 
> > 
> > I think that calling sum() on an empty vector should be a perfectly legal
> > operation, and should return 0. Similar with prod() and 1. That's
> > according to the principle of least surprise, and it's also consistent
> > with Matlab and Octave.
> > The same code with a VectorXcd, by the way, at least triggers the
> > assertion in Redux.h:186, but with double and int as scalar type,
> > v.head(0).sum() just silently return v(0). It was pure coincidence that
> > I noticed this behavior.
> > 
> > The same argument of course also applies to trace() and det() of
> > zero-sized matrices.
> > 
> > I would have liked to submit a patch, but honestly, I got lost in all the
> > template magic... I would be really grateful if one of the gurus could
> > fix this.
> > 
> > If you wonder why someone would want to take the sum of an empty vector
> > in the first place; well, of course I don't have code like
> > v.head(0).sum() with a literal 0, but I do have something like
> > 
> > double f(const VectorXd& v, int n)
> > {
> >  assert(n >= 0 && n <= v.size());
> >  return foo(v.head(n).sum()) + bar(v.tail(v.size() - n).sum());
> > }
> > 
> > which should be legal for n == 0 and n == v.size(), and in these cases I
> > naturally expect sum() to return 0 for an empty segment.
> > If reductions of empty vectors remain unsupported, I would have to
> > clutter my code with tons of ifs and special-case-treatments.
> > 
> > Cheers
> > Martin




Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/