Python 1
Python 1
Numpy, Matplotlib
Rajiv Bhutani
XIM Bhubaneswar
2018-2020
REPL
• Fast Prototyping
• Takes single expression from user, processes it, outputs it
• Helps in exploratory programming and debugging, because
you can see the result before deciding what expression to
input next
• Vs
• In [2]: hello()
• Hello Hello
• In[3]: pv = 100
…: pv*(1+0.015)**3
• Out[3]: 104.56783749999997
More Examples
• def fv_f(pv,r,n):
• """Objective: Estimate present value
• formula : pv = fv/((1+r)^n)
• fv: future value
• r: discount rate
• n: time period
• """
• return pv*(1+r)**n
• In[4]: fv_f(100,0.1,2)
• Out[4]: 121.00000000000001
• In[5]: Help(fv_f)
• Help on function fv_f in module __main__:
• fv_f(pv, r, n)
• Objective: Estimate present value
• formula : pv = fv/((1+r)^n)
• fv: future value
• r: discount rate
• n: time period
For Loop
• In[6]: import numpy as np
• In[7]: cashFlows=np.array([-100,50,40,30])
• In[12]: y=(7,8,9)
• In[13]: y[0]=2
• Traceback (most recent call last):
• File "<ipython-input-51-f39ee00d3d8d>", line 1, in <module>
• y[0]=10
• TypeError: 'tuple' object does not support item assignment
• In[14]: type(x)
• Out[14]: list
• In[15]: type(y)
• Out[15]: tuple
Npv Functions
• def npv_f(rate, cashflows):
• total = 0.0
• for i in range(0,len(cashflows)):
• total += cashflows[i]/(1+rate)**i
• return total
• In[16]: r=0.035
• In[17]: cashflows=[-100,-30,10,40,50,45,20]
• In[18]: npv_f(r,cashflows)
• Out[18]: 14.158224763725372
Npv Functions from Excel
• NPV function from Excel is actually a PV function, i.e. it can be applied only to
future
• def npv_Excel(rate, cashflows):
• total = 0.0
• for i, cashflow in enumerate(cashflows):
• total += cashflow/(1+rate)**(i+1)
• return total
• In[16]: r=0.035
• In[17]: cashflows=[-100,-30,10,40,50,45,20]
• Write in editor:
• if grade>=90:
• print('A')
• elif grade>=80:
• print('B')
• elif grade>=70:
• print('C')
• elif grade>=60:
• print('D')
• else:
• print('F')
• >>>dir(math)
Working with Python
• To find all string related functions
• >>>dir(‘’)
• >>>x=np.array([[1,2],[5,6],[7,9]])
• >>>print(x)
• >>> y=x.flatten()
• >>>print(x)
• >>>print(y)
• >>>x2=np.reshape(y,[2,3])
• >>>print(x2)
Working with Numpy
• >>>x=np.array([[1,2,3],[3,4,6]])
• >>>np.size(x)
• 6
• >>>np.size(x,0)
• 2
• >>>np.size(x,1)
• 3
• >>>np.size(x,2)
• Error
• >>>np.std(x)
• 1.5723301886761005
• >>>np.std(x,0)
• array([1. , 1. , 1.5])
• >>>np.std(x,1)
• array([0.81649658, 1.24721913])
• >>>Total=x.sum()
• 19
Random Numbers with Numpy
• >>>z=np.random.rand(50)
• >>>print(z)
• >>>y=np.random.normal(50)
• >>>print(y)
• >>>y=np.random.normal(500)
• >>>print(y)
• >>>y=np.random.normal(size=50)
• >>>print(y)
• >>>mean(z)
• >>>avg(z)
• >>>average(z)
• n=1024
• X=np.random.normal(0,1,n)
• Y=np.random.normal(0,1,n)
• scatter(X,Y)
• show()