Monday, June 7, 2021

Python Number and Math modules

  

`math` 

main module for mathematical computations 

>>> import math 

>>> math.cos(math.pi / 4) 

0.70710678118654757 

>>> math.log(1024, 2) 

10.0 

`random` 

You can use this module to generate random values. 

 

>>> import random 

>>> random.choice(['apple', 'pear', 'banana']) 

'apple' 

>>> random.sample(range(100), 10)   # sampling without replacement 

[30, 83, 16, 4, 8, 81, 41, 50, 18, 33] 

>>> random.random()    # random float 

0.17970987693706186 

>>> random.randrange(6)    # random integer chosen from range(6) 

4 

`statistics` 

Module for statistical calculation 

>>> import statistics 

>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] 

>>> statistics.mean(data) 

1.6071428571428572 

>>> statistics.median(data) 

1.25 

>>> statistics.variance(data) 

1.3720238095238095 

`decimal` 

Can be used by applications that requires precise calculations. 
 
This calculates 5% tax on a 70 cent phone. 

>>> from decimal import * 

>>> round(Decimal('0.70') * Decimal('1.05'), 2) 

Decimal('0.74') 

>>> round(.70 * 1.05, 2) 

0.73 
 
Performs modulo calculations and equality test that are unsuitable for binary float point. 

>>> Decimal('1.00') % Decimal('.10') 

Decimal('0.00') 

>>> 1.00 % 0.10 

0.09999999999999995 

 

>>> sum([Decimal('0.1')]*10) == Decimal('1.0') 

True 

>>> sum([0.1]*10) == 1.0 

False 
 
Performs very precise calculations. 

>>> getcontext().prec = 36 

>>> Decimal(1) / Decimal(7) 

Decimal('0.142857142857142857142857142857142857') 

functools 

>>> from functool import reduce 

>>> reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) 

15 

>>>  

No comments:

Post a Comment