Using mathematical function with Python | applied electronics engineering

Latest

Using mathematical function with Python

By Applied Electronics - Monday, February 13, 2017 No Comments
Python is an open source programming software and language. It is like Matlab but free. You can do anything you can do with Matlab. For scientific program writing and mathematics you can use the math module. There are many python packages you can use for scientific and mathematics programming such as Numpy. But you can also use basic python math module without installing the various packages. Package like Numpy supports various mathematics construct such as matrices and are optimized for speed(see Basics of Matrices in Numpy). In long term you should use them. See the advantage of learning Numpy, Scipy and Matplotlib with examples.

So if you want to work with mathematical functions such as sin, cos, exponential etc then you need to use the math module. To use the math module, you need to import the module.

import math

Once you imported the math module you need to specify the functions which you want to use. For example say you wanted to use sin function. Then you would use it using the dot convention of object oriented programming. Like so,

In[13]: math.sin(2)
Out[13]: 0.9092974268256817

Optionally you could also use the from keyword to import just the sin function like so,

In[20]: from math import sin
In[21]: sin(2)
Out[21]: 0.9092974268256817

 This was about how to use the mathematical function with python.

Now to know which math functions are supported and their keywords you can use the dir function. This is as follows.

import math

dir(math)
Out[24]: 
['__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'trunc'] 

So in this way you can use the mathematical function in python

No Comment to " Using mathematical function with Python "