[cctbxbb] normalize() is not safe

Luc Bourhis luc_j_bourhis at mac.com
Tue May 2 00:59:52 PDT 2017


Hi,

> On 2 May 2017, at 07:44, Pavel Afonine <pafonine at lbl.gov> wrote:
> 
> If memory serves norm of a zero vector is zero, isn't it? So naively I'd expect that function to return zero, not fail in obscure way..
> 
> Broadly speaking, norm is length. Length of a zero vector is zero.
> 
> So my proposal would be to treat zero vectors as special case and do the right thing for it.

If the current implementation

      vec3 normalize() const
      {
        return (*this) / length();
      }

was to be replaced by the following, as Pavel proposed if I understand correctly,

if(length() == 0) raise scitbx::error(“a zero vector cannot be normalised”);
return (*this)/length();

this may not result in any performance hit in fact. Indeed the compiler would still be allowed to inline normalize and then the processor branch prediction unit may realise the branch throwing the exception is hardly ever taken, and take advantage of that to reorder calculations to, in effect, make the code equivalent to the current implementation. But this is the point: the current implementation is guaranteed to be optimal whether the rewrite may be optimal. So if this function appears in a critical path, you would need to check there is no performance hit.

Best wishes,

Luc

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://phenix-online.org/pipermail/cctbxbb/attachments/20170502/0b058afc/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 3581 bytes
Desc: not available
URL: <http://phenix-online.org/pipermail/cctbxbb/attachments/20170502/0b058afc/attachment.p7s>


More information about the cctbxbb mailing list