Skip to content

Commit

Permalink
Add section about floating points to Python
Browse files Browse the repository at this point in the history
  • Loading branch information
bkaestner committed Oct 8, 2015
1 parent 94b0106 commit 7b05cbb
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions rules/0270-Python.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,38 @@ If you have some ideas for this section, head over to [GitHub][GH-python-issue].
[python-pep20]: https://www.python.org/dev/peps/pep-0020/ "The Zen of Python"
[GH-python-issue]: https://github.com/bkaestner/codewars-rules/issues/7

### Floating point tests

As written above, one shouldn't use `assert_equals` on floating point
values, since the user might use another order of addition, and adding
floating point numbers isn't associative:

``` python
print ("Is + associative in Python on double values?")
print (1 + (1e-12 + 3e-12) == (1 + 1e-12) + 3e-12)

print (" :( ")
```

Therefore, you should plan a little threshold. I usually use `1e-12`,
which is *good enough*, or `1e-6` if the kata is about approximative
results. Just change the value below to whatever you feel is best.
Just keep in mind that any value lower than `1e-15` is bogus.

``` python
def assertFuzzyEquals(actual, expected, msg=""):
import math

if expected == 0:
inrange = math.fabs(actual) <= 1e-12
else:
inrange = math.fabs((actual - expected) / expected) <= 1e-12

if msg == "":
msg = "Expected value near {:.12f}, but got {:.12f}"
msg = msg.format(expected, actual)

return Test.expect(inrange, msg)
```

<!--- this is only a placeholder -->

0 comments on commit 7b05cbb

Please sign in to comment.