Lo que todo programador debería saber sobre aritmética de punto flotante
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add Python cheatsheet.

authored by

Juanjo Conti and committed by
Michael Borgwardt
c99021a4 7167239e

+38
+38
content/languages/python.html
··· 1 + --- 2 + title: Floating-point cheat sheet for Python 3 + description: Tips for using floating-point and decimal numbers in Python 4 + --- 5 + 6 + Floating-Point Types 7 + -------- 8 + Almost all platforms map Python floats to [IEEE 754](/formats/fp/) 9 + double precision. 10 + 11 + f = 0.1 12 + 13 + Decimal Types 14 + ------------- 15 + Python has an [arbitrary-precision](/formats/exact/) decimal type named <code>Decimal</code> in the <code>decimal</code> module, which 16 + also allows to choose the [rounding mode](/errors/rounding/). 17 + a = Decimal('0.1') 18 + b = Decimal('0.2') 19 + c = a + b # returns a Decimal representing exactly 0.3 20 + 21 + 22 + How to Round 23 + ------------ 24 + To get a string: 25 + "%.2f" % 1.2399 # returns "1.24" 26 + "%.3f" % 1.2399 # returns "1.240" 27 + "%.2f" % 1.2 # returns "1.20" 28 + To print to standard output: 29 + print "%.2f" % 1.2399 # just use print and string formatting 30 + If you need a specific [rounding mode](/errors/rounding/) and other parameters can be defined in a Context object: 31 + getcontext().prec = 7 32 + 33 + Resources 34 + --------- 35 + * [Floating Point Arithmetic: Issues and Limitations](http://docs.python.org/tutorial/floatingpoint.html) 36 + * [The decimal module](http://docs.python.org/library/decimal.html) 37 + * [Context objects](http://docs.python.org/library/decimal.html#context-objects) 38 + * [String formatting in Python](http://docs.python.org/library/stdtypes.html#string-formatting-operations)