aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Xithrius <[email protected]>2021-02-03 02:08:11 -0800
committerGravatar GitHub <[email protected]>2021-02-03 02:08:11 -0800
commitc068ffe458db507325cf7c75061db5e7f0f28e68 (patch)
tree6b6e44cc79ec1f30e639feff00166b6d317aced5
parentMerge pull request #1390 from ChrisLovering/Handle-OverflowErrors (diff)
parentMention math.isclose and add an example (diff)
Merge pull request #1395 from python-discord/wookie184-floats-tag
Add tag on float imprecision
-rw-r--r--bot/resources/tags/floats.md20
1 files changed, 20 insertions, 0 deletions
diff --git a/bot/resources/tags/floats.md b/bot/resources/tags/floats.md
new file mode 100644
index 000000000..7129b91bb
--- /dev/null
+++ b/bot/resources/tags/floats.md
@@ -0,0 +1,20 @@
+**Floating Point Arithmetic**
+You may have noticed that when doing arithmetic with floats in Python you sometimes get strange results, like this:
+```python
+>>> 0.1 + 0.2
+0.30000000000000004
+```
+**Why this happens**
+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**
+ 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
+>>> math.isclose(0.1 + 0.2, 0.3)
+True
+>>> decimal.Decimal('0.1') + decimal.Decimal('0.2')
+Decimal('0.3')
+```
+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).