Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

triu generates nan when called on matrices with infinite values #4859

Closed
gaberosser opened this issue Jul 10, 2014 · 1 comment
Closed

triu generates nan when called on matrices with infinite values #4859

gaberosser opened this issue Jul 10, 2014 · 1 comment

Comments

@gaberosser
Copy link

In numpy 1.8.1, I've just found some strange behaviour.

Summary: when calling np.triu on a matrix, inf entries in the discarded region get converted to nan. This broke my code unexpectedly.

import numpy as np
a = np.zeros((4, 4))
a[1:, 2] = np.inf
a
>>>array([[  0.,   0.,   0.,   0.],
          [ inf,   0.,   0.,   0.],
          [ inf,   0.,   0.,   0.],
          [ inf,   0.,   0.,   0.]])

np.triu(a)
>>>array([[  0.,   0.,   0.,   0.],
          [ nan,   0.,   0.,   0.],
          [ nan,   0.,   0.,   0.],
          [ nan,   0.,   0.,   0.]])

Also posted on stackexchange: https://stackoverflow.com/questions/24678932/numpy-triu-generates-nan-when-called-on-matrices-with-infinite-values

@jaimefrio
Copy link
Member

We could use boolean indexing instead of multiplication, and may even make it faster if done properly:

In [18]: arr = np.random.rand(1000, 1000)

In [19]: %timeit np.tri(1000) * arr # this is was np.triu currently does
100 loops, best of 3: 8.74 ms per loop

In [28]: %%timeit # this would be the boolean approach
   ....: mask = ~np.tri(1000, dtype=bool)
   ....: out = arr.copy()
   ....: out[mask] = 0
   ....:
100 loops, best of 3: 7 ms per loop

I have only done limited testing, but haven't found any faster way of doing this while keeping a pure Python implementation. Ideas are welcome! There may be an extra ms to shave if we change np.tri to take an inverse kwarg so that it produces the negated mask directly.

Anyway, if there is no major objection to this approach, I'll have a PR ready later today.

juliantaylor added a commit that referenced this issue Jul 10, 2014
BUG: inf turned to nan when calling np.triu/np.tril, fixes #4859
juliantaylor pushed a commit to juliantaylor/numpy that referenced this issue Jul 16, 2014
Replaces the current method to zero items, from multiplication to
using `np.where`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants