Skip to content

Does the compiler ignore computations that are multiplied by zero? #24364

Answered by jakevdp
Rasmuskh asked this question in Q&A
Discussion options

You must be logged in to vote

In general, no it does not, because multiplication by zero cannot safely be ignored. Consider this function:

def f(a, b):
  return a + 0 * b

def f_ignore_mult_by_zero(a, b):
  return a

When b is finite, the functions return the same results:

f(1.0, 1.0) # 1.0
f_ignore_mult_by_zero(1.0, 1.0) # 1.0

However, when b is NaN or inf, the functions return different results:

f(1.0, np.inf) # NaN
f_ignore_mult_by_zero(1.0, np.inf) # 1.0

One of the key goals of the compiler is to not optimize in a way that will change program outputs, and so the compiler will not elide multiplication by zero.

If you want "ignore multiplication by zero" semantics, you can do this explicitly with lax.cond; e.g. some…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@Rasmuskh
Comment options

@jakevdp
Comment options

@Rasmuskh
Comment options

Answer selected by Rasmuskh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants