<jupyter_start><jupyter_text>链接在此: [第三章 - 数字日期和时间](https://python-cookbook-3rd-edition.readthedocs.io/zh_CN/latest/chapters/p03_numbers_dates_times.html)  rounding numerical values<jupyter_code>tips_round = '''
    1  =>  .x      ---  1.56,  1 => 1.6
    2  =>  .xx     ---  1.565, 2 => 1.57
   -1  =>  XX(X)X  ---  1565, -1 => 1570
'''

''' using round '''

# >=5 
round(1.34, 1),\
round(1.35, 1),\
round(1.36, 1)

# in-mid => closest even nums
round(21.5, 0),\
round(20.5, 0), 

# neg val 
round(1759,  0),\
round(1759, -1),\
round(1759, -2)
''' formatting '''

num = 1.2456

f'{num:.1f}'
f'{num:.2f}'
f'{num:.3f}'
''' advanced formatting '''

# syntax: '[<>^]?width[,]?(.digits)?'
num = 1234.5678

f'{num:.2f}'

f'{num:>15.2f}'
f'{num:<15.2f}'
f'{num:^15.2f}'

f'{num:,}'
f'{num:,.1f}'

f'{num:e}'
f'{num:.2e}'
f'{num:.2E}'<jupyter_output><empty_output><jupyter_text>accurate decimal calc<jupyter_code>4   + 2
4.1 + 2.1  # 6.19999999...
# control everything!  (well, decimal calc)

from decimal import Decimal, localcontext

Decimal(1.3)   + Decimal(1.7)    # do use str (NOT int/float)
Decimal('1.3') + Decimal('1.7')

# precision 

with localcontext() as ctx:
    ctx.prec = 20
    Decimal(10 / 7)
# there's another problem 

from decimal import Decimal 
from math import fsum

# for decimal, everything is fine 
sum(
    [Dec(1.23e+18), Dec(1), Dec(-1.23e+18)]
)

# for normal num, nope!
sum(
    [1.23e+18, 1, -1.23e+18]  # the '1' disappeared!!
)

# use 'fsum' instead!
fsum(
    [1.23e+18, 1, -1.23e+18]  # got what you want ~
)<jupyter_output><empty_output><jupyter_text>bin,oct,hex with format<jupyter_code>x = 1200

# conv | format
bin(x), format(x, 'b') 
oct(x), format(x, 'o')
hex(x), format(x, 'x')

# conv back
int(bin(x), 2)
int(oct(x), 8)
int(hex(x), 16)
# neg-num
format(-1234, 'b')
format(-1234, 'x')

# no-neg (unsigned)
format(2 ** 32 + (-1234), 'b')
format(2 ** 32 + (-1234), 'x')<jupyter_output><empty_output><jupyter_text>pack/unpack large integers (from bytes)<jupyter_code>from sys import byteorder

# let's see the byteorder first 
x = 0x01020304
x.to_bytes(4, 'big')
x.to_bytes(4, 'little')

# or.. 
byteorder


# unpack 

larrrge = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
int.from_bytes(larrrge, 'big')
int.from_bytes(larrrge, 'little')  # default (well.. still need specifing)

# and pack

largeee = 25395299529
largeee.to_bytes(8, 'big')
largeee.to_bytes(8, 'little')<jupyter_output><empty_output><jupyter_text>complex num<jupyter_code>import math 
import cmath 
import numpy 


a = complex(2, 4)
b = complex(3, 1)

# attr
a.real, a.imag, a.conjugate()

# arithmetic
a + b, a - b
a * b, a / b

# about -1 
try:
    math.sqrt(-1)
except ValueError:
    cmath.sqrt(-1)

# cos, sin, tan 
cmath.sin(a), cmath.cos(a), cmath.exp(a)

# with numpy 
num = numpy.array([2 + 3j, 4 + 5j, 6 - 8j])
num * 2 
num - 2
numpy.sin(num)<jupyter_output><empty_output><jupyter_text>NaN & Infinity<jupyter_code>''' create '''

# NaN 
n1 = float('nan')
n2 = float('Nan')
n3 = float('-NaN')

# Infinity 
i1 = float('-inf')
i2 = float('Infinity')
i3 = float('-infinity')


''' identify '''

from math import isnan, isinf 

for i in [n1, n2, n3]:
    isnan(i)
    
for i in [i1, i2, i3]:
    isinf(i)
''' nan, inf will propagate in calculations.
'''

# inf 
inff = float('inf')
inff + 1, inff * 10

# nan    
c = float('nan')
c + 1, c - 1

# nan - certain opt
float('inf') / float('inf')    
float('+inf') + float('-inf')  

# nan - not equals to itself 
float('nan') == float('nan')<jupyter_output><empty_output><jupyter_text>fraction<jupyter_code>from fractions import Fraction as F

a = F(1, 2)
b = F(6, 7)

a.numerator
a.denominator

a + b, a - b
a * b, a / b

F(34, 20).limit_denominator(10)

# frac to float 
float(a)
float(b)

# conv float to frac
flt_num = 5.33
F(
    *flt_num.as_integer_ratio()
)<jupyter_output><empty_output><jupyter_text>calc with *NumPy*<jupyter_code>import numpy as np

na = np.array([1, 2, 3, 4])
nb = np.array([5, 6, 7, 8])

# apply to each one 
na * nb 
na / nb

# func as well 
thrib = lambda x: x**3
thrib(na)

# math func 
np.sqrt(na)
np.log10(na)

# large array 
np.zeros(shape=(10000, 10000), dtype=float)
m = np.matrix([
    [1, -2, 3],
    [4, -3, 6],
    [7,  8, 9],
])

m.T 
m.I; 

v = np.matrix([
    [2], 
    [3],
    [4],
])

m * v


np.linalg.det(m)
np.linalg.eigvals(m)
np.linalg.solve(m, v)<jupyter_output><empty_output><jupyter_text>rand num<jupyter_code>import random as rd

val = [1, 2, 3, 4, 5, 6]

rd.choice(val),\
rd.choice(val),\
rd.choice(val)

rd.sample(val, 3),\
rd.sample(val, 6)  # !> len(val)

rd.shuffle(val)    # rand the list in-place 
'changed: ', val

rd.randint(0, 10)  # [ 0, 10 ]

rd.random()        # [ 0.0, 1.0 )

rd.getrandbits(50) # (bin|int)

rd.seed()          # init seed 
rd.seed(b'wal<PASSWORD>') # init seed (again)<jupyter_output><empty_output><jupyter_text>basic time conv<jupyter_code>from datetime import (
    timedelta, datetime 
)

# --- timedelta ---

s = timedelta(days=3, hours=5)

s
s.days
s.seconds
s.total_seconds()

# --- datetime ---  

start = datetime(2015, 8, 31)

start
start + timedelta(days=100)

# --- today --- 

now = datetime.today()

now
now + timedelta(days=31)
from datetime import datetime 
from pytz import timezone, utc  # use other modules instead!

# --- leap years --- 

datetime(2000, 3, 1) - datetime(2000, 2, 29) 
datetime(2015, 3, 1) - datetime(2015, 2, 28)

# --- str to date --- 

fut = datetime.strptime('2019-6-30', '%Y-%M-%d')
now = datetime.now()

(fut - now)
(fut - now).days

# --- timezone --- 

date     = datetime(2012, 12, 21, 9, 30, 0)
date_loc = timezone('US/Central').localize(a_date)

date
date_loc

date_trans_again = a_date_loc.astimezone(timezone('Asia/Shanghai'))
date_trans_again

# --- timezone: UTC --- 

date
date.astimezone(utc)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1943298969072165, 'fraction_numerical': 0.0661512027491409, 'mean_word_length': 3.5441061670569867, 'pattern_counts': {'":': 0, '<': 44, '<?xml version=': 0, '>': 53, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '272335', 'license': 'Unlicense', 'n_tokens_mistral': 2859, 'n_tokens_neox': 2584, 'n_words': 572, 'path': 'Chapter03 - Full.ipynb', 'repo_name': 'codingEzio/code_py_book_cookbook', 'size': '5813'}