Python math module
godarda@gd:~$ python3 ... >>> import math >>> math.pi 3.141592653589793 >>> math.e 2.718281828459045 >>> math.exp(1) 2.718281828459045 >>> math.inf inf >>> math.nan nan
>>> math.factorial(10) 3628800 >>> math.fmod(7,3) 1.0 >>> math.fmod(10.5,3.5) 0.0 >>> math.fsum([1,1.1,3.14]) 5.24 >>> math.modf(10.5) (0.5, 10.0)
>>> math.gcd(18,21) 3 >>> math.lcm(24,36) 72
Logarithm functions
>>> import math >>> math.log(2) 0.6931471805599453 >>> math.log10(2) 0.3010299956639812 >>> math.log2(2) 1.0 >>> math.log(2,10) 0.30102999566398114 >>> math.log(2,2) 1.0
sqrt(), cbrt() and pow() functions
>>> import math >>> math.sqrt(25) 5.0 >>> math.sqrt(20) 4.47213595499958 >>> math.cbrt(27) 3.0000000000000004 >>> math.pow(2,10) 1024.0 >>> 2**10 1024
round(), floor(), ceil() and trunc() functions
>>> round(2.3) 2 >>> round(2.8) 3 >>> round(-2.3) -2 >>> round(-2.8) -3
>>> abs(2.3) 2.3 >>> abs(-2.3) 2.3
>>> import math >>> math.floor(2.3) 2 >>> math.floor(2.8) 2 >>> math.floor(-2.3) -3 >>> math.floor(-2.8) -3
>>> math.ceil(2.3) 3 >>> math.ceil(2.8) 3 >>> math.ceil(-2.3) -2 >>> math.ceil(-2.8) -2
>>> math.trunc(2.3) 2 >>> math.trunc(2.8) 2 >>> math.trunc(-2.3) -2 >>> math.trunc(-2.8) -2
>>> math.fabs(2.3) 2.3 >>> math.fabs(-2.3) 2.3
Explicit type conversion using int() and float() functions
>>> int(7.99)
7
>>> float(7)
7.0
>>> a=int('10')
>>> b=int('20')
>>> c=a+b
>>> c
30
>>> float('inf')
inf
>>> float('nan')
nan
>>> import math
>>> math.isinf(0)
False
>>> math.isinf(float('inf'))
True
>>> math.isnan(float('nan'))
True
Number conversion using int(), bin(), oct(), and hex() functions
>>> n=255
>>> print("Binary",bin(n))
Binary 0b11111111
>>> print("Octal",oct(n))
Octal 0o377
>>> print("Hexadecimal",hex(n))
Hexadecimal 0xff
>>> n="11111111"
>>> print("Decimal",int(n,2))
Decimal 255
>>> print("Octal",oct(int(n,2)))
Octal 0o377
>>> print("Hexadecimal",hex(int(n,2)))
Hexadecimal 0xff
>>> n=0o377
>>> print("Decimal",int(n))
Decimal 255
>>> print("Hexadecimal",hex(n))
Hexadecimal 0xff
>>> n=0Xff
>>> print("Decimal",int(n))
Decimal 255
>>> print("Octal",oct(n))
Octal 0o377
>>> print("Binary",bin(n))
Binary 0b11111111
Comments and Reactions
What Next?
Python Trigonometric Functions
How to use Python help utility
How to compile a Python program using the py_compile module
Advertisement