# <span style="color: #B40486">BASIC PYTHON FOR RESEARCHERS</span>

_by_ [**_Megat Harun Al Rashid bin Megat Ahmad_**](https://www.researchgate.net/profile/Megat_Harun_Megat_Ahmad)  
last updated: April 14, 2016

-------
## _<span style="color: #29088A">1. Mathematical Operations</span>_


Simple mathematical operations are part of the native _Python_ features but advanced mathematical tools can be accessed by importing the <span style="color: #0000FF">**math**</span> library.


```python
from math import *
```

The syntax above when executed allows the usage of mathematical functions available in the <span style="color: #0000FF">**math**</span> library. The `'*'` means everything _i.e._ all functions in the <span style="color: #0000FF">**math**</span> library are imported and can be used. It is also possible to import a specific function and rename it but this will be explored in the forthcoming tutorials.

Now let us do some simple mathematical operations:

***
### **_1.1 Addition and Substraction_**


```python
12+7
```




    19




```python
23 + 67 - 34
```




    56



Trailing white space is ignored by _Python_. Operation on floating points is automatic but can also be declared using the <span style="color: #088A08">**float&#40;&#41;**</span> function:


```python
12.34 + 8
```




    20.34




```python
float(13) - 7
```




    6.0



***
### **_1.2 Multiplication and Division_**


```python
12 * 38
```




    456




```python
9 / 3
```




    3




```python
15/6
```




    2



Division between integers will give a truncated integer value (rather than the number being rounded up). It is good practice to use floating point number instead, by declaring one of the integer with decimal point.


```python
15.0/6
```




    2.5



***
### **_1.3 Exponent and Root_**

Exponent can be declared by using `'e'` or `'E'` letters with no trailing space:


```python
3E12
```




    3000000000000.0




```python
7.9e-12 * 6
```




    4.74e-11



Power (and root) can be declared by using the `'**'` character. For instance, the operation for $2^3$ is:


```python
2**3
```




    8



and for $\sqrt[3]{8}$ (in which it should produces the value $2$).


```python
8**1.0/3
```




    2.6666666666666665



but here it did not produce the value of 2 because the term $8^{1.0}$ is evaluated first before being divided by the number $3$. Herein users need to know that _Python_ follows the usual order of operations in mathematical expressions. The standard order of operations is expressed in the following enumeration:

1. Exponent and Root.
2. Multiplication and Division.
3. Addition and Substraction.

Lower order can be prioritize by using parenthesis.


To get the correct value for $8^{\frac{1}{3}}$, the $1.0/3$ operation need to be parenthesized which means that it will be evaluated first instead of the operation $8^{1.0}$.


```python
8**(1.0/3)
```




    2.0



This floating value can be change into an integer by declaring it as integer using the <span style="color: #088A08">**int&#40;&#41;**</span> function:


```python
int(8**(1.0/3))
```




    2



Power and root operations can also be performed by using their respective built-in functions:


```python
sqrt(9)
```




    3.0



which is the operation for $\sqrt{9}$ whereas...


```python
pow(2,3)
```




    8.0



...is the operation for $2^3$. Users can also used <span style="color: #088A08">**pow&#40;&#41;**</span> function to perform root operation.


```python
pow(9,(1.0/2))   
```




    3.0




```python
pow(8.2,0.43)
```




    2.4713824398960362



The <span style="color: #088A08">**log&#40;$x$&#41;**</span> and <span style="color: #088A08">**log10&#40;$x$&#41;**</span> functions respectively return natural and base 10 logarithmic for <span style="color: #088A08">**$x$**</span> value. 


```python
log(100)
```




    4.605170185988092




```python
log10(1000)
```




    3.0



The function <span style="color: #088A08">**log&#40;$x$,$y$&#41;**</span> returns base <span style="color: #088A08">$y$</span> for <span style="color: #088A08">$x$</span> value. Exponential value can directly be used using the `'e'` letter.


```python
log(1000,8)
```




    3.3219280948873626




```python
e
```




    2.718281828459045




```python
log(e)
```




    1.0



***
### **_1.4 Trigonometric functions_**

_Python_ only accepts radians value for trigonometric operations. For instance, an angle with a value of $60^o$ needs to be converted to radians before trigonometric operation. This include the usage of <span style="color: #088A08">$\pi$</span> which can directly be used using the `'pi'` term.


```python
pi
```




    3.141592653589793




```python
sin(60*pi/180)
```




    0.8660254037844386



Floating point arithmatic is not exact because decimal fraction cannot be represented exactly as binary (base 2) fraction in the computer hardware logical operation as evidenced by the two instances below (where both operations should give exact value of $0.5$)


```python
sin(30*pi/180)
```




    0.49999999999999994




```python
cos(60*pi/180)
```




    0.5000000000000001



Apart from operating with <span style="color: #088A08">$\pi$</span> users can also used the <span style="color: #088A08">**radians&#40;$x$&#41;**</span> function which converts <span style="color: #088A08">$x$</span> degrees into radians (and there is also <span style="color: #088A08">**degrees&#40;$x$&#41;**</span> function that convert radians into degrees).


```python
sin(radians(60))
```




    0.8660254037844386




```python
degrees(0.5*pi)
```




    90.0




```python
sin(radians(30))**2 + cos(radians(30))**2
```




    1.0



#### <span style="color: #F5DA81; background-color: #610B4B">Example 1.1</span>: What is the value of $\theta$ in degree if y = 1 and x = 1.732 in the Figure 1 below



                                            Figure  1

#### <span style="color: red; background-color: yellow-light">$Answer$</span>: 


```python
atan2(1,1.732)*180/pi
```




    30.000727780827372



Arc tangent value can be obtained using the <span style="color: #088A08">**atan2&#40;$y$,$x$&#41;**</span> function that give the angle <span style="color: #088A08">$\theta$</span> value in radian. Alternatively, users can calculate the value of <span style="color: #088A08">$y$/$x$</span> first and then use it as the <span style="color: #088A08">$x$</span> argument for <span style="color: #088A08">**atan&#40;$x$&#41;**</span> function.


```python
atan(1/1.732)*180/pi
```




    30.000727780827372



#### <span style="color: #F5DA81; background-color: #610B4B">Example 1.2</span>: From the values given in Example 1.1 what is the hypotenuse value of the triangle and calculate $\theta$ using this hypotenuse value and the given $x$ value.

#### <span style="color: red; background-color: yellow-light">$Answer$</span>: 


```python
hypot(1.732,1)
```




    1.9999559995159892




```python
degrees(acos(1.732/2))
```




    30.002910931188026



Further mathematical functions on <span style="color: #0000FF">**math**</span> library can be found in https://docs.python.org/2/library/math.html

***
### **_1.5 Variables_**

A numerical value can be assigned to a variable by using the `'='` operation. For instance:


```python
x = 34.5
```

which means that <span style="color: #088A08">$x$</span> has been assigned a value of `34.5`. In _Python_, variable type is specified during the assignment of the variable and need not be declared beforehand _e.g._ if an integer is assigned to a variable, then the variable is of integer type. Variables can be operated much like numerics.


```python
y = 23.9
z = 12
add = y + z - 5.7
add
```




    30.2



Variable names must consist of continuous list of letters, numbers and underscore but cannot start with a number. Multiple variables can be assigned in one line by separating each variables and values with comma.


```python
i,j,k = 23,45,17
```


```python
i
```




    23




```python
k
```




    17



#### <span style="color: #F5DA81; background-color: #610B4B">Exercise 1.1</span>: What is the profit before and after tax (45%) for a course:
* Title: “How to use MATLAB like Pro”.
* Participants: limited to 21 persons.
* Fee: RM 15,000/person.
* Duration: half a week.

#### <span style="color: red; background-color: yellow-light">$Solution$</span>:

`**********************************************************************`


```python
profit = 21*15000
profit
```




    315000




```python
profit_after_tax = profit*45.0/100
profit_after_tax
```




    141750.0



`**********************************************************************`

***
### **_1.6 Advanced Topic: Symbolic Computation_**

In symbolic computation, result of mathematical operation is represented exactly by unevaluated variables left in symbolic form. For instance, the mathematical operation of $\sqrt{8}$ will give result of a value of 2.83 but in symbolic computation, the result will be $2\sqrt{2}$. _Python_ has symbolic mathematics (or sometime called computer algebra system or simply CAS) library called <span style="color: #0000FF">**sympy**</span>. For a start, let try to symbolically evaluate $\sqrt{8}$:


```python
import sympy as sp

sp.sqrt(8)
```




    2*sqrt(2)



the term **<span style="color: #088A08">import</span> sympy <span style="color: #088A08">as</span> sp** allows the calling of <span style="color: #0000FF">**sympy**</span> functions simply by typing **sp.{function name}**. The expression can be operated upon, _e.g._ multiplication with 23.4 gives:


```python
sp.sqrt(8)*23.4
```




    46.8*sqrt(2)



Operation on expression, _e.g._ <span style="color: #088A08">$x$ **+** $y$ **+** $x$</span> that produce <span style="color: #088A08">2$x$ **+** $y$</span>, can be performed by initially declaring <span style="color: #088A08">$x$</span> and <span style="color: #088A08">$y$</span> as symbolic representations:


```python
x, y = sp.symbols('x y')
x + y + x
```




    2*x + y



The resulting expression can be assigned to variable and operated upon:


```python
expr = x + y + y
2*expr
```




    2*x + 4*y




```python
x*expr
```




    x*(x + 2*y)



The <span style="color: #0000FF">$sympy$</span> library allows users to works on derivatives, integrals, solve equations, matrices, and much more. Some of the examples are: 

* Solving the <span style="color: #0000FF">**$3x^2$ + $45x$ - $84$ = $0$**</span> equation


```python
sp.solve(3*x**2 + 45*x - 84, x)
```




    [-15/2 + sqrt(337)/2, -sqrt(337)/2 - 15/2]



* Differentiation: <span style="color: #0000FF">$\frac{d}{dx}(cos(x)e^x)$</span>


```python
sp.diff(sp.cos(x)*sp.exp(x), x)
```




    -exp(x)*sin(x) + exp(x)*cos(x)



* Integration: <span style="color: #0000FF">$\int{e^{x}sin(x)dx}$</span>


```python
sp.integrate(sp.exp(x)*sp.sin(x), x)
```




    exp(x)*sin(x)/2 - exp(x)*cos(x)/2



* Computing <span style="color: #0000FF">$$\int_{-\infty}^\infty{\frac{1}{1 + x^{2}}}dx$$</span>


```python
sp.integrate(1/(1 + x**2), (x, -sp.oo, sp.oo))
```




    pi



* Finding the determinant of the matrix <span style="color: #0000FF">$$\left[ \begin{array}{cc}
1 & 3 \\
6 & 2\end{array} \right]$$</span>


```python
M = sp.Matrix(([1, 3], [6, 2]))
```


```python
M
```




    Matrix([
    [1, 3],
    [6, 2]])




```python
M.det()
```




    -16



* Finding the product of <span style="color: #0000FF">$$\left[ \begin{array}{cc}
1 & 3 \\
6 & 2\end{array} \right]\left[ \begin{array}{cc}
4 \\
8\end{array} \right]$$</span>


```python
M1 = sp.Matrix(([1, 3], [6, 2]))
M2 = sp.Matrix(([4],[8]))
M1*M2
```




    Matrix([
    [28],
    [40]])



Further <span style="color: #0000FF">$sympy$</span> features can be found in http://docs.sympy.org/latest/tutorial/index.html

375d27dedb7c3db8d71be708c63ea340d43983e6
ipynb
Jupyter Notebook
Tutorial 1 - Mathematical Operation.ipynb
megatharun/basic-python-for-researcher
9f1fb1b545f52ed1eab43d21616eadf85791e625
Artistic-2.0
2017-04-04T22:59:25.000Z
2017-04-04T22:59:25.000Z
.ipynb_checkpoints/Tutorial 1 - Mathematical Operation-checkpoint.ipynb
megatharun/basic-python-for-researcher
9f1fb1b545f52ed1eab43d21616eadf85791e625
Artistic-2.0
.ipynb_checkpoints/Tutorial 1 - Mathematical Operation-checkpoint.ipynb
megatharun/basic-python-for-researcher
9f1fb1b545f52ed1eab43d21616eadf85791e625
Artistic-2.0
2018-03-11T19:50:37.000Z
2020-04-18T19:51:10.000Z
Qwen/Qwen-72B
1. YES
2. YES