python cookbook 2 數字 日期 時間(2)

來源:互聯網
上載者:User

標籤:

5.位元組到大整數的轉換

#擁有128位長的16個元素的位元組字串。>>> data = b‘\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004‘>>> len(data)16將bytes解析為整數,使用 int.from_bytes() 方法#僅使用與python3#位元組順序規則(little或big)僅僅指定了構建整數時的位元組的低位高位相片順序。>>> int.from_bytes(data, ‘little‘)69120565665751139577663547927094891008>>> int.from_bytes(data, ‘big‘)94522842520747284487117727783387188>>> 將一個大整數轉換為一個位元組字串,使用 int.to_bytes() 方法,並像下面這樣指定位元組數和位元組順序:>>> x=94522842520747284487117727783387188>>> x.to_bytes(16,‘big‘)b‘\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004‘>>> x.to_bytes(16,‘little‘)b‘4\x00#\x00\x01\xef\xcd\x00\xab\x90x\x00V4\x12\x00‘>>> 使用 int.bit_length() 方法來決定需要多少位元組位來儲存這個值>>> x=94522842520747284487117727783387188>>> x.bit_length()117

6.複數的數學運算

複數可以用使用函數 complex(real, imag) 或者是帶有尾碼j的浮點數來指定

>>> a = complex(2, 4)>>> b= 3-5j>>> a(2+4j)>>> b(3-5j)對應的實部、虛部和共軛複數>>> a.real2.0>>> a.imag4.0>>> a.conjugate()(2-4j)所有常見的數學運算都可以工作>>> a+b(5-1j)>>> a-b(-1+9j)>>> a/b(-0.4117647058823529+0.6470588235294118j)>>> abs(a)4.47213595499958執行其他的複數函數比如正弦、餘弦或平方根,使用cmath模組>>> import cmath>>> cmath.sin(a)(24.83130584894638-11.356612711218173j)>>> cmath.cos(a)(-11.36423470640106-24.814651485634183j)>>> cmath.exp(a)(-4.829809383269385-5.5920560936409816j)Python的標準數學函數確實情況下並不能產生複數值>>> import math>>> math.sqrt(-1)Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: math domain error>>> import cmath>>> cmath.sqrt(-1)1j

7.無窮大與NaN

建立或測試正無窮、負無窮或NaN(非數字)的浮點數

>>> a = float(‘inf‘)>>> b = float(‘-inf‘)>>> c = float(‘nan‘)>>> ainf>>> b-inf>>> cnan使用 math.isinf() 和 math.isnan() 函數檢測>>> math.isinf(a)True>>> math.isnan(c)True>>> math.isinf(b)True無窮大數在執行數學計算的時候會傳播>>> a+45inf>>> a*10inf>>> 10/a0.0有些操作時未定義的並會返回一個NaN結果。>>> a/anan>>> a+bnanNaN值會在所有操作中傳播,而不會產生異常。>>> c+11nan>>> c/3nan>>> c*3nanNaN值的一個特別的地方時它們之間的比較操作總是返回False。>>> d=float(‘nan‘)>>> c==dFalse>>> c is dFalse由於這個原因,測試一個NaN值得唯一安全的方法就是使用 math.isnan()

8.分數運算

fractions模組可以被用來執行包含分數的數學運算。

>>> from fractions import Fraction>>> a =Fraction(5,4)>>> b = Fraction(7, 16)>>> aFraction(5, 4)>>> bFraction(7, 16)>>> print a+b27/16>>> print a*b35/64取分子分母>>> c= a*b>>> c.numerator35>>> c.denominator64換算成小數>>> float(c)0.546875限制分母>>> c.limit_denominator(8)#分母不超過8的最接近的分數Fraction(4, 7)float轉換為分數>>> x=1.75>>> y = Fraction(*x.as_integer_ratio())>>> yFraction(7, 4)


python cookbook 2 數字 日期 時間(2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.