1

In my python testing script, I want to assert if all elements of numpy array are either very close to 1.0 or equal to 0.0. The array looks like this:

[[0.9999999991268851 1.0000000223517418 0.999999986961484 ...,
  0.9999999841675162 1.0000000074505806 0.9999999841675162]
 [0.9999999991268851 1.0000000223517418 0.999999986961484 ...,
  0.9999999841675162 1.0000000074505806 0.9999999841675162]
 [0.9999999991268851 1.0000000223517418 0.999999986961484 ...,
  0.9999999841675162 1.0000000074505806 0.9999999841675162]
 ..., 
 [1.0000000198488124 1.0000000074505806 1.000000002568413 ...,
  0.9999999888241291 0.9999999925494194 0.0]
 [1.000000011001248 0.9999999850988388 0.9999999869323801 ...,
  1.0000000186264515 0.9999999925494194 0.0]
 [1.000000011001248 0.9999999850988388 0.9999999869323801 ...,
  1.0000000186264515 0.9999999925494194 0.0]]

I thought of using numpy.allclose or numpy.array_equal, but neither makes sense here. ideally, the function should be able to be used in a testing scenario

3
  • What is "very close to"? Commented Dec 15, 2015 at 0:59
  • I think you are looking at something like numpy's assert_almost_equal. See the docs for examples. Commented Dec 15, 2015 at 1:02
  • Why doesn't allclose make sense? (It broadcasts!) Commented Dec 15, 2015 at 1:06

2 Answers 2

3

You can get the 0 elements and mask them out using boolean indexing. Once that's done, np.allclose is exactly what you want:

zeros = arr == 0.0
without_zeros = arr[~zeros]
np.allclose(without_zeros, 1, ...)
Sign up to request clarification or add additional context in comments.

Comments

0

The simplest thing I can think of would just be to iterate over every element of the array and test if it is either close to one or equal to zero:

import numpy as np

arr = np.array([[0.9999999991268851, 1.0000000223517418, 0.999999986961484],
                [1.0000000186264515, 0.9999999925494194, 0.0]])

def is_one_or_zero(arr):
  for elem in np.nditer(arr):
    if not (elem == 0 or np.isclose(1.0, elem)):
      return False
  return True

print is_one_or_zero(arr) # Should be True
arr[0, 0] = 1.01
print is_one_or_zero(arr) # Should be False

4 Comments

I'd iterate over arr.flat instead of assuming it's a 2D array.
@mgilson I changed it to use np.nditer. Is there any advantage to arr.flat versus np.nditer?
I dunno :-). Probably not a huge difference between the two -- though it's been a while since I've worked with numpy heavily, so I could be wrong here...
arr.flat is a fairly simple iterator that always iterates in c-contiguous order. nditer is capable of much more complex operations, see here. On a side note, python loops for numpy arrays is usually not a good idea due to the severe python performance penalty.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.