Python |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Python - Mathematical Operators/Functions
These are the math functions that are commonly used (you may use this as a quick cheatsheet). There are more math functions. Some of the functions from math package does almost same thing as native operator/functions but with more accuracy. You may refer to official Python document : 9.2. math — Mathematical functions for further details.
Examples 1 > Basic Operator >>> 2 + 5 7
>>> 3 - 5 -2
>>> 2 * 3 6
>>> 2 / 3 0.6666666666666666
>>> pow(2,3) 8
>>> pow(2.0,3.0) 8.0
>>> 2 ** 3 8
>>> 7 % 3 1
Examples 2> math package >>> import math
>>> math.exp(1) 2.718281828459045
>>> math.sqrt(2) 1.4142135623730951
Examples 3> complex number
>>> a = 1+2j
>>> b = complex(2,3)
>>> a (1+2j)
>>> b (2+3j)
>>> a+b (3+5j)
>>> a*b (-4+7j)
>>> a/b (0.6153846153846154+0.07692307692307691j)
>>> a.real 1.0
>>> a.imag 2.0
>>> a.conjugate() (1-2j)
>>> import cmath
>>> cmath.phase(a) 1.1071487177940904
>>> cmath.polar(a) (2.23606797749979, 1.1071487177940904)
>>> cmath.rect(2.23606797749979,1.1071487177940904) (1.0000000000000002+2j)
Example 4 > Complex Number (Same as Example 3, but run in *.py script)
import cmath
a = 1+2j b = complex(2,3)
print('a = ',a) print('b = ',b) print('a+b = ',a+b) print('a*b = ',a*b) print('a/b = ',a/b) print('a.real = ',a.real) print('a.imag = ',a.imag) print('a.conjugate() = ',a.conjugate()) print('cmath.phase(a) = ',cmath.phase(a)) print('cmath.polar(a) = ',cmath.polar(a)) print('cmath.rect(2.23606797749979,1.1071487177940904) = ', cmath.rect(2.23606797749979,1.1071487177940904))
Result :---------------------------------
a = (1+2j) b = (2+3j) a+b = (3+5j) a*b = (-4+7j) a/b = (0.6153846153846154+0.07692307692307691j) a.real = 1.0 a.imag = 2.0 a.conjugate() = (1-2j) cmath.phase(a) = 1.1071487177940904 cmath.polar(a) = (2.23606797749979, 1.1071487177940904) cmath.rect(2.23606797749979,1.1071487177940904) = (1.0000000000000002+2j)
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||