這個是使用最多的,剛看了round()的使用解釋,也不是很容易懂。round()不是簡單的四捨五入的處理方式。
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two
multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and
round(1.5) is 2).
>>> round(2.5) 3.0 >>> round(-2.5) -3.0 >>> round(2.675) 3.0 >>> round(2.675,2) 2.67
round()如果只有一個數作為參數,不指定位數的時候,返回的是一個整數,而且是最靠近的整數。一般情況是使用四捨五入的規則,但是碰到捨入的後一位為5的情況,如果要取捨的位數前的數是偶數,則直接捨棄,如果奇數這向上取捨。看下面的示例:
>>> round(2.555,2) 2.56 >>> round(2.565,2) 2.56 >>> round(2.575,2) 2.58 >>> round(2.585,2) 2.58
效果和round()是一樣的。
>>> a = ("%.2f" % 2.555)
>>> a
'2.56'
>>> a = ("%.2f" % 2.565)
>>> a
'2.56'
>>> a = ("%.2f" % 2.575)
>>> a
'2.58'
>>> a = ("%.2f" % 2.585)
>>> a
'2.58'
>>> a = int(2.5)
>>> a
2
python默認的是17位精度,也就是小數點後16位,但是這裡有一個問題,就是當我們的計算需要使用更高的精度(超過16位小數)的
時候該怎麼做呢?
>>> from decimal import *
>>> print(getcontext())
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
>>> getcontext().prec = 50
>>> b = Decimal(1)/Decimal(3)
>>> b
Decimal('0.33333333333333333333333333333333333333333333333333')
>>> c = Decimal(1)/Decimal(7)
>>> c
Decimal('0.14285714285714285714285714285714285714285714285714')
>>> float(c)
0.14285714285714285
默認的context的精度是28位,可以設置為50位甚至更高,都可以。這樣在分析復雜的浮點數的時候,可以有更高的自己可以控
制的精度。其實可以留意下context裡面的這rounding=ROUND_HALF_EVEN 參數。ROUND_HALF_EVEN, 當half的時候,靠近
even.
>>> a = ("%.30f" % (1.0/3))
>>> a
'0.333333333333333314829616256247'
可以顯示,但是不准確,後面的數字基本沒有意義。
既然說到小數,就必然要說到整數。一般取整會用到這些函數:
這個不說了,前面已經講過了。一定要注意它不是簡單的四捨五入,而是ROUND_HALF_EVEN的策略。
取大於或者等於x的最小整數。
去小於或者等於x的最大整數。
>>> from math import ceil, floor >>> round(2.5) 2 >>> ceil(2.5) 3 >>> floor(2.5) 2 >>> round(2.3) 2 >>> ceil(2.3) 3 >>> floor(2.3)
Ubuntu 14.04安裝Python 3.3.5 http://www.linuxidc.com/Linux/2014-05/101481.htm
CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm