forked from brazzy/floating-point-gui.de
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
--- | ||
title: Floating-point cheat sheet for Python | ||
description: Tips for using floating-point and decimal numbers in Python | ||
--- | ||
|
||
Floating-Point Types | ||
-------- | ||
Almost all platforms map Python floats to [IEEE 754](/formats/fp/) | ||
double precision. | ||
|
||
f = 0.1 | ||
|
||
Decimal Types | ||
------------- | ||
Python has an [arbitrary-precision](/formats/exact/) decimal type named <code>Decimal</code> in the <code>decimal</code> module, which | ||
also allows to choose the [rounding mode](/errors/rounding/). | ||
a = Decimal('0.1') | ||
b = Decimal('0.2') | ||
c = a + b # returns a Decimal representing exactly 0.3 | ||
|
||
|
||
How to Round | ||
------------ | ||
To get a string: | ||
"%.2f" % 1.2399 # returns "1.24" | ||
"%.3f" % 1.2399 # returns "1.240" | ||
"%.2f" % 1.2 # returns "1.20" | ||
To print to standard output: | ||
print "%.2f" % 1.2399 # just use print and string formatting | ||
If you need a specific [rounding mode](/errors/rounding/) and other parameters can be defined in a Context object: | ||
getcontext().prec = 7 | ||
|
||
Resources | ||
--------- | ||
* [Floating Point Arithmetic: Issues and Limitations](http://docs.python.org/tutorial/floatingpoint.html) | ||
* [The decimal module](http://docs.python.org/library/decimal.html) | ||
* [Context objects](http://docs.python.org/library/decimal.html#context-objects) | ||
* [String formatting in Python](http://docs.python.org/library/stdtypes.html#string-formatting-operations) |