Assert float comparison

I am taking a look at callbacks and schedules and I have noticed that the combine_scheds function starts with

assert sum(pcts) == 1.

pcts is a list of floats, [0.3, 0.7] in this example. I have always been told to avoid comparing floats because of the unpredictable results, and instead test:

abs(a - b) < delta

(or assert abs(sum(pcts) - 1.) < delta in this case).

I have also looked for this function in the fastai Github repository, but didn’t find it. Is the code correct as it is? Is the code in the repository different?

(I am looking at a frame from Lesson 9 at 2h 10’ 49".)

Edit: thanks @Kaspar for noticing that I’m a silly boy and forgot the “abs”. I also wrote the other one wrong for good measure.

almost. abs(a-b)<delta would be better


Haha, more than “better”, I’d say! You absolutely need that “abs”, of course. I promise I have it in my code :sweat_smile::sweat_smile:

Thanks for pointing this out :slight_smile:

Probably better to use assertAlmostEqual from unittest, rather than reinventing the wheel (and possibly forgetting the abs :wink: )

There’s a similar function in NumPy too.

1 Like