On Saturday, July 21, 2018 at 11:28:44 AM UTC-7, Jeroen Demeyer wrote:
>
> I was benchmarking some code (in particular the density() method of 
> matrices) and noticed code of the form 
>
> if not x.is_zero(): 
>
> however, that's a lot slower than doing just 
>
> if x: 
>
> So, this makes me wonder: what is the reason for the is_zero() method? 
> Are there classes where "x.is_zero()" is not the same as "not x"? 
>
> I would think there is a difference in expressed intention: The python 
bool(x) just asks to convert x to a boolean (implemented via __nonzero__). 
While custom and the naming of the method suggest it should be roughly 
something like (x != 0) that's not enforced. 

I can imagine that at some point there might be a type out there for which 
the two do not agree, so if I want to check that something is zero, I'd 
probably just defensively use is_zero (if I know that method is provided -- 
I don't think it's a standard python method).

>From a stylistic point of view I always dislike "if x:" when x is not 
obviously a boolean already. It's just not how we write mathematics. 
However, if code needs to optimized for speed, style quickly goes out the 
window.
 

-- 
You received this message because you are subscribed to the Google Groups 
"sage-devel" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-devel+unsubscr...@googlegroups.com.
To post to this group, send email to sage-devel@googlegroups.com.
Visit this group at https://groups.google.com/group/sage-devel.
For more options, visit https://groups.google.com/d/optout.

Reply via email to