[TIP] doctest and floats
bignose+hates-spam at benfinney.id.au
Mon Mar 10 15:24:55 PDT 2008
"Tim Head" <betatim at gmail.com> writes:
> if you want to test a function that returns a float, what is the
> "one way" to write that down in a doctest?
The same "one way" as for any other use of floats: Never compare
floating-point numbers for equality.
> It feels wrong to write
> >>> foo(0.1)
It will also cause the doctest to fail on platforms where that's not
the representation of 0.1. It also violates correct usage of floats,
by asking (via doctest) for an equality comparison between float
Instead, do what people *should* be doing to compare floats anyway:
never compare floats for equality, instead compare the difference
against an epsilon value.
>>> epsilon = 1e-12
>>> want = 0.1
>>> got = foo(0.1)
>>> abs(want - got) < epsilon
\ “Ignorance more frequently begets confidence than does |
`\ knowledge.” —Charles Darwin, _The Descent of Man_, 1871 |
More information about the testing-in-python