diff options
| author | 2021-02-03 10:00:42 +0000 | |
|---|---|---|
| committer | 2021-02-03 10:00:42 +0000 | |
| commit | 9c1e5fd22e71f919bcbb7e2215430a0b4d518310 (patch) | |
| tree | 6b6e44cc79ec1f30e639feff00166b6d317aced5 | |
| parent | Add tag on float imprecision (diff) | |
Mention math.isclose and add an example
| -rw-r--r-- | bot/resources/tags/floats.md | 9 |
1 files changed, 5 insertions, 4 deletions
diff --git a/bot/resources/tags/floats.md b/bot/resources/tags/floats.md index 4b0651930..7129b91bb 100644 --- a/bot/resources/tags/floats.md +++ b/bot/resources/tags/floats.md @@ -8,12 +8,13 @@ You may have noticed that when doing arithmetic with floats in Python you someti Internally your computer stores floats as as binary fractions. Many decimal values cannot be stored as exact binary fractions, which means an approximation has to be used. **How you can avoid this** -If you require an exact decimal representation, you can use the [decimal](https://docs.python.org/3/library/decimal.html) or [fractions](https://docs.python.org/3/library/fractions.html) module. Here is an example using the decimal module: + You can use [math.isclose](https://docs.python.org/3/library/math.html#math.isclose) to check if two floats are close, or to get an exact decimal representation, you can use the [decimal](https://docs.python.org/3/library/decimal.html) or [fractions](https://docs.python.org/3/library/fractions.html) module. Here are some examples: ```python ->>> from decimal import Decimal ->>> Decimal('0.1') + Decimal('0.2') +>>> math.isclose(0.1 + 0.2, 0.3) +True +>>> decimal.Decimal('0.1') + decimal.Decimal('0.2') Decimal('0.3') ``` -Note that we enter in the number we want as a string so we don't pass on the imprecision from the float. +Note that with `decimal.Decimal` we enter the number we want as a string so we don't pass on the imprecision from the float. For more details on why this happens check out this [page in the python docs](https://docs.python.org/3/tutorial/floatingpoint.html) or this [Computerphile video](https://www.youtube.com/watch/PZRI1IfStY0). |