Skip to content

Commit

Permalink
Add Python cheatsheet.
Browse files Browse the repository at this point in the history
  • Loading branch information
jjconti authored and Juan Jose Conti committed Aug 16, 2010
1 parent 7167239 commit 02cddbd
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions content/languages/python.html
@@ -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)

0 comments on commit 02cddbd

Please sign in to comment.