[Tutor] unitest with random inputs
steve at pearwood.info
Wed Jul 19 12:56:49 EDT 2017
On Wed, Jul 19, 2017 at 06:08:57PM +0200, Sydney Shall wrote:
> For the second error, regarding 'nan' finding 'nan', I received the
> following output.
> FAIL: test_nan_in_capitalsadvanced (__main__.TestPOC)
> Traceback (most recent call last):
> line 323, in test_nan_in_capitalsadvanced
> self.assertIn('nan', self.capitalsadvanced)
> AssertionError: 'nan' not found in array([ 12026.72641072,
> 12434.53700436, 12185.56314119, ...,
> 12488.04714281, 12479.4662866 , 12310.66016998])
NANs are tricky to work with.
To check whether a list contains a NAN value, you cannot reliably use
"nan in list". How do we fix that?
To begin with, we need to use an actual floating point NAN, not the
string "nan". So we can try this:
float('nan') in list
Alas, that's not enough. As Peter discussed earlier, for technical
reasons, "Not A Number" floating point values (NANs) are designed to
always fail equality tests. And for other technical reasons, Python
tests for object identity before equality tests when evaluating the "in"
operator. Don't worry if you don't understand the gory details yet: the
message to take home is that NANs are special, and you cannot *reliably*
test for them with the "in" operator.
*will not work* reliably, if at all.
Instead, we can create our own test for a NAN:
self.assertTrue(any(math.isnan(x) for x in self.capitalsadvanced))
Make sure you run "import math" at the top of your module.
(I haven't tested that code myself, so please try it, and if it doesn't
work for some reason, let us know on the mailing list and somebody can
But... I'm rather surprised that you need this test. Are you sure that
your array capitalsadvanced will *always* contain at least one Not A
Number value? Unless you put one in yourself, NANs generally indicate
that a mathematical error has occurred somewhere.
More information about the Tutor