KEMBAR78
Python Tutorial m7Ou6Vm | PDF | Zero Of A Function | Matrix (Mathematics)
0% found this document useful (0 votes)
22 views32 pages

Python Tutorial m7Ou6Vm

This document is a basic tutorial on Python, covering fundamental concepts such as variable assignment, using libraries like numpy and scipy, and performing mathematical operations. It includes examples of data structures like lists and matrices, as well as visualization techniques using matplotlib. The tutorial is designed to be run in Google Colab, requiring users to install specific libraries to execute the provided code snippets.

Uploaded by

NAGA GANESH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views32 pages

Python Tutorial m7Ou6Vm

This document is a basic tutorial on Python, covering fundamental concepts such as variable assignment, using libraries like numpy and scipy, and performing mathematical operations. It includes examples of data structures like lists and matrices, as well as visualization techniques using matplotlib. The tutorial is designed to be run in Google Colab, requiring users to install specific libraries to execute the provided code snippets.

Uploaded by

NAGA GANESH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Python_Tutorial 12/01/25, 12:12 PM

1. Basic tutorial on Python


Taken from Chapra and Clough, Applied Numerical Methods with Python, McGraw
Hill 2022. The images are from the presentations associated with the book.

You need to install the following additional libraries to run the cells in this Notebook.

1. numpy
2. scipy
3. matplotlib

You can upload this file on Google Colabs and run the cells. You will have to login
with your google account. All the relevant libraries are generally available on Colabs.

Assignment of values to variable names


In [1]: a = 2
print(type(a))

<class 'int'>

In [2]: A = 6.0
print(type(A))

<class 'float'>

In [3]: print("a = ", a, "\n", "A = ", A)

a = 2
A = 6.0

In [13]: y = 3.54; z = 1/3; Z = 5//3

In [14]: print(y, z, Z)
print(type(y))
print(type(Z))

3.54 0.3333333333333333 1
<class 'float'>
<class 'int'>

In [15]: c = 2 + 4j
type(c)

Out[15]: complex

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 1 of 32
Python_Tutorial 12/01/25, 12:12 PM

Using modules
In [16]: import math

In [17]: print(math.pi)

3.141592653589793

In [7]: import scipy.constants as pc

In [20]: pc.h # Planck constant

Out[20]: 6.62607015e-34

Storing more than one item


list , tuple , and array

In [21]: Xarray - Xlist

Out[21]: array([0., 0., 0., 0., 0.])

In [19]: import numpy as np

In [20]: Xlist = [12.2, 19.9, 13.6, 8.4, 1.1]


Xarray = np.array([12.2, 19.9, 13.6, 8.4, 1.1])
Xarray - np.array(Xlist)

Out[20]: array([0., 0., 0., 0., 0.])

In [22]: print(type(Xlist), type(Xarray))

<class 'list'> <class 'numpy.ndarray'>

Matrix is special type of array

In [24]: A = [[1, 2], [2, 4]]


print(type(A))

A = np.matrix(A)
print(type(A))
print(A.shape)

<class 'list'>
<class 'numpy.matrix'>
(2, 2)

In [25]: w = np.matrix([[12.2, 10.9, 13.6, 8.4, 11.1]])


w.shape

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 2 of 32
Python_Tutorial 12/01/25, 12:12 PM

Out[25]: (1, 5)

In [29]: w = np.matrix([[1], [2], [2.3], [4.4]])


w.shape

Out[29]: (4, 1)

Accessing elements of matrices or arrays


In [14]: print(A)
print(A[0, 0])
print(A[0, :])
print(A[0, -1])

[[1 2]
[2 4]]
1
[[1 2]]
2

In [27]: print(Xlist)
print(Xlist[1:])
print(Xlist[:-1])

[12.2, 19.9, 13.6, 8.4, 1.1]


[19.9, 13.6, 8.4, 1.1]
[12.2, 19.9, 13.6, 8.4]

In [28]: print(A)
print(A[0, 0:2]) # the upper limit 2 is not included

[[1 2]
[2 4]]
[[1 2]]

Specific functions
arange , linspace , and logspace

np.arange(x1, x2, dx)

does not include the last item `x2`

In [29]: x = np.arange(0, 1, 0.1)


print(x)

[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

In [30]: print(np.arange(0, 1+0.1, 0.1))

[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 3 of 32
Python_Tutorial 12/01/25, 12:12 PM

using np.linspace(x1, x2, n)

Note: includes the last value x2

In [31]: import numpy as np


d = np.linspace(1, 100, 8) # divide 1 to 100 into 8 parts that are equally spac
print(d)

[ 1. 15.14285714 29.28571429 43.42857143 57.57142857


71.71428571 85.85714286 100. ]

np.logspace(logx1, logx2, n)

logx1 = −1 (1)
logx2 = 2 (2)
n=4 (3)

n values from 10−1 to 102 at log10 values of −1, 0, 1, 2

In [32]: np.logspace(-1, 2, 4)

Out[32]: array([ 0.1, 1. , 10. , 100. ])

Mathematical operations
(Image from Chapra and Clough)

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 4 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [24]: import numpy as np


np.pi * 0.5**2 / 4

Out[24]: 0.19634954084936207

To check the order of operations

In [25]: result1 = 0.5**2

In [26]: result2 = np.pi * result1

In [27]: finalresult = result2/4


print(finalresult)

0.19634954084936207

When in doubt just use brackets!!

Note the use of brackets below

In [35]: x = 3; y = 2; z = 1.5

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 5 of 32
Python_Tutorial 12/01/25, 12:12 PM

-x ** y

Out[35]: -9

In [36]: (-x)**y

Out[36]: 9

In [30]: x ** y ** z

Out[30]: 22.361590938430393

In [31]: x**(y**z)

Out[31]: 22.361590938430393

In [32]: (x**y)**z

Out[32]: 27.0

Calculations with matrix objects


In [37]: a = np.matrix('1, 2, 3, 4, 5')
a
a.shape

Out[37]: (1, 5)

In [38]: b = np.matrix('2; 4; 6; 8; 10')


b
b.shape

Out[38]: (5, 1)

In [39]: a*b # inner product

Out[39]: matrix([[110]])

In [40]: b*a # outer product

Out[40]: matrix([[ 2, 4, 6, 8, 10],


[ 4, 8, 12, 16, 20],
[ 6, 12, 18, 24, 30],
[ 8, 16, 24, 32, 40],
[10, 20, 30, 40, 50]])

More operations with matrices


In [44]: A = np.matrix('1 2 3; 4 5 6; 7 8 9')

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 6 of 32
Python_Tutorial 12/01/25, 12:12 PM

a = np.matrix('1 2 3');
b = np.matrix('4; 5; 6')

In [43]: a*A

Out[43]: matrix([[30, 36, 42]])

In [45]: A*b

Out[45]: matrix([[ 32],


[ 77],
[122]])

In [36]: A*a # you will get an error

--------------------------------------------------------------------------
-
ValueError Traceback (most recent call last
)
Cell In[36], line 1
----> 1 A*a # you will get an error

File ~/miniconda3/envs/fenics2019.1/lib/python3.9/site-packages/numpy/matr
ixlib/defmatrix.py:221, in matrix.__mul__(self, other)
218 def __mul__(self, other):
219 if isinstance(other, (N.ndarray, list, tuple)) :
220 # This promotes 1-D vectors to row vectors
--> 221 return N.dot(self, asmatrix(other))
222 if isscalar(other) or not hasattr(other, '__rmul__') :
223 return N.dot(self, other)

ValueError: shapes (3,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

In [39]: A*A # matrix multiplication

Out[39]: matrix([[ 30, 36, 42],


[ 66, 81, 96],
[102, 126, 150]])

In [ ]: A.transpose() # switch rows and columns

In [ ]: np.multiply(A, A) # item by item multiplication

Calculations with Array objects


In [46]: a = np.array([1, 2, 4])
b = np.array([4, 5, 6])

In [47]: a*b # element by element multiplication

Out[47]: array([ 4, 10, 24])

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 7 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [48]: a.dot(b) # dot product

Out[48]: 38

In [49]: np.cross(a, b) # cross product

Out[49]: array([-8, 10, -3])

Using help
Using [command]? . Generally very unhelpful. Better if used with LLM.

In [1]: import numpy as np


np.cross?

Built-in functions

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 8 of 32
Python_Tutorial 12/01/25, 12:12 PM

For example, the expression:

v=√ tanh(√
mg cd g
cd m t)

In [3]: from math import *


from numpy import *

In [51]: import math


g = 9.81; m = 68.1; cd = 0.25;
t = 10;
v = math.sqrt(m*g/cd)*math.tanh(math.sqrt(cd*g/m)*t)
print(v)

49.42136691869133

Define function on our own

In [7]: import math


def velocity(t):
g = 9.81; m = 68.1; cd = 0.25
v = math.sqrt(m*g/cd)*math.tanh(math.sqrt(cd*g/m)*t)
return v

t = 10
v = velocity(t)
print(v)

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 9 of 32
Python_Tutorial 12/01/25, 12:12 PM

print('{0:5.6f}'.format(v))
print('velocity = ', v, 'm/s')

49.42136691869133
49.421367
velocity = 49.42136691869133 m/s

Vectorization of output

In [8]: tm = np.linspace(0, 20, 11)


print(tm)

[ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18. 20.]

In [9]: import numpy as np


tm = np.linspace(0, 20, 11)
print(tm)

g = 9.81; m = 68.1; cd = 0.25


v = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*tm)
print(v)

[ 0. 2. 4. 6. 8. 10. 12. 14. 16. 18. 20.]


[ 0. 18.72918885 33.11182504 42.07622706 46.95749513 49.42136692
50.61747935 51.18714999 51.45599493 51.58232304 51.64156286]

In [10]: print(type(tm))
print(type(np.array([0, 1, 2])))

<class 'numpy.ndarray'>
<class 'numpy.ndarray'>

Making Plots using pyplot

In [11]: import matplotlib.pyplot as plt


plt.plot(tm, v)
plt.title("Velocity as a function of time")
plt.xlabel('Time in seconds')
plt.ylabel('Velocity in m/s')
plt.grid()

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 10 of 32
Python_Tutorial 12/01/25, 12:12 PM

Making scatter plots. There are various colors and symbols

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 11 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [12]: import matplotlib.pyplot as plt


%matplotlib inline
%config InlineBackend.figure_format='retina'

#plt.plot(tm, v, marker='o')
plt.scatter(tm, v)
plt.title("Velocity as a function of time")
plt.xlabel('Time in seconds')
plt.ylabel('Velocity in m/s')
plt.grid()

Making multiple plots


In [13]: import numpy as np
tm = np.linspace(0, 20, 11)

g = 9.81; m = 68.1; cd = 0.25


t = 10
v = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*tm)

cd = 0.35
v1 = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*tm)

plt.plot(tm, v, ls ='-', marker='D', label='cd = 0.25')

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 12 of 32
Python_Tutorial 12/01/25, 12:12 PM

plt.plot(tm, v1, ls ='--', marker='o', label='cd = 0.35')


#plt.scatter(tm, v)
#plt.scatter(tm, v)
plt.title("Velocity as a function of time")
plt.xlabel('Time in seconds')
plt.ylabel('Velocity in m/s')
plt.legend(loc='lower right')
plt.grid()

Coding in Python
You can write the commands and save them in filename.py . Then run the
command python filename.py . Else work everything in jupyter notebook

Python functions - 1
def function_name(arguments):

""" docstring """

statements

return output_results (or statement)

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 13 of 32
Python_Tutorial 12/01/25, 12:12 PM

docstring essentially are multiline comments

In [15]: import math


import scipy.constants as pc

def freefall(t, m, cd):


"""
function freefall: computes jumper velocity
with second order drag
input arguments:
t = time (s), m = mass (kg), cd = drag coefficient (kg/m)
returns velocity in m/s
"""
g = pc.g # get g from SciPy
return math.sqrt(m*g/cd)*math.tanh(math.sqrt(cd*g/m)*t)

In [16]: freefall(12, 68.1, 0.25)

Out[16]: 50.608007473466444

Another function

In [4]: import numpy as np


def stats(x):
n = len(x)
avg = np.average(x)
s = np.std(x)
return n, avg, s

y = [8, 5, 10, 12, 6, 7, 5, 4]


n, avg, s = stats(y)
print(n, avg, s)

8 7.125 2.5708704751503917

Variable scope
In the function below x is defined outside the function but is accessible from within.
However, s is defined inside the function and is not accessible from outside. In a
call to the previous function stats we had calculated s .

In [5]: s

Out[5]: np.float64(2.5708704751503917)

In [6]: def adder(a, b):


print('x = ', x)
#print('s = ', s)
s = a + b
#print('s = ', s)

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 14 of 32
Python_Tutorial 12/01/25, 12:12 PM

f = s;
return s

x = 88
c = 1
d = 5
print('sum = ', adder(c, d))
print('s = ', s)
print('f = ', f)

x = 88
sum = 6
s = 2.5708704751503917
--------------------------------------------------------------------------
-
NameError Traceback (most recent call last
)
Cell In[6], line 14
12 print('sum = ', adder(c, d))
13 print('s = ', s)
---> 14 print('f = ', f)

NameError: name 'f' is not defined

However, we can define a variable within a function with a global scope in which case
it can be made accessible from outside.

In [18]: def adder(a, b):


global x
x = 90
s = a + b
return s

c = 1
d = 5
print('sum = ', adder(c, d))
print('x = ', x)
print('s = ', s)

sum = 6
x = 90
s = 10

Input-Output
s = input('prompt string')

In [19]: Ts = input('enter value of temperature in degC: ')


print(type(Ts))

enter value of temperature in degC: 25


<class 'str'>

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 15 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [72]: Tin = float(Ts)


print('Temperature in degF is ', '{0:6.1f}'.format(Tin*1.8 + 32))

Temperature in degF is 74.2

In [20]: print(20, '{0:10.3f}'.format(123.456), 10)


print("{0:6.1f} {1:6.6f}".format(12.3, 45.678))

20 123.456 10
12.3 45.678000

Reading from file


In [24]: np.loadtxt('testdata.txt')

Out[24]: array([[ 0. , -0.109, 53.8 ],


[ 9. , 0. , 53.6 ],
[18. , 0.178, 53.5 ],
[27. , 0.339, 53.5 ],
[36. , 0.373, 53.4 ],
[45. , 0.441, 53.1 ],
[54. , 0.461, 52.7 ],
[63. , 0.348, 52.4 ],
[72. , 0.127, 52.2 ],
[81. , -0.18 , 52. ],
[90. , -0.588, 52. ]])

In [21]: import numpy as np


import matplotlib.pyplot as plt

time, x, y = np.loadtxt('testdata.txt', unpack=True)


plt.plot(time, x, c = 'k')
plt.twinx()
plt.plot(time, y, c='k', ls='--')
plt.grid()

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 16 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [22]: import numpy as np


time,x,y = np.loadtxt('testdata.csv',unpack=True,delimiter=',')
print(time[1],x[1],y[1])

9.0 0.0 53.6

Writing data files


In [27]: np.array([time,x,y]).transpose()

Out[27]: array([[ 0. , -0.109, 53.8 ],


[ 9. , 0. , 53.6 ],
[18. , 0.178, 53.5 ],
[27. , 0.339, 53.5 ],
[36. , 0.373, 53.4 ],
[45. , 0.441, 53.1 ],
[54. , 0.461, 52.7 ],
[63. , 0.348, 52.4 ],
[72. , 0.127, 52.2 ],
[81. , -0.18 , 52. ],
[90. , -0.588, 52. ]])

In [35]: import numpy as np


time,x,y = np.loadtxt('testdata.csv',unpack=True,delimiter=',')
np.savetxt('testdata1.txt',np.array([time,x,y]).transpose()
,fmt=['%5d','%7.6f','%5.1f'])

In [40]: # for storing arrays in one script and retreiving in another

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 17 of 32
Python_Tutorial 12/01/25, 12:12 PM

import numpy as np
time,x,y = np.loadtxt('testdata.csv',unpack=True,delimiter=',')
X = np.array([time,x,y]).transpose()
np.save('Xdata.npy',X)
X2=np.load('Xdata.npy')
print(X2)

[[ 0. -0.109 53.8 ]
[ 9. 0. 53.6 ]
[18. 0.178 53.5 ]
[27. 0.339 53.5 ]
[36. 0.373 53.4 ]
[45. 0.441 53.1 ]
[54. 0.461 52.7 ]
[63. 0.348 52.4 ]
[72. 0.127 52.2 ]
[81. -0.18 52. ]
[90. -0.588 52. ]]

Structured Programming
1. Decisions (selection)
2. Loops (repetition)

if condition: statements

condition gives a T/F result

if grade >= 60: print('passing grade')

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 18 of 32
Python_Tutorial 12/01/25, 12:12 PM

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 19 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [21]: import numpy as np


np.sign(25.6)

Out[21]: 1.0

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 20 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [22]: np.sign(-1.76)

Out[22]: -1.0

In [5]: np.sign(0)

Out[5]: 0

In [ ]: if x > 0
{
return 1
}

In [23]: # one-way if
def sgn(x):
if x > 0:
print('x = ', x)
return 1

print(sgn(-1))

None

In [24]: # two-way if
def sgn(x):
if x > 0:
return 1
else:
return -1
print(sgn(-1))
print(sgn(0))

-1
-1

In [27]: # multi-alternative if
def sgn(x):
print('x = ', x)
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0

print(sgn(0))

x = 0
0

Loops
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 21 of 32
Python_Tutorial 12/01/25, 12:12 PM

Using for loop with range

In [28]: range(1, 13, 3)

Out[28]: range(1, 13, 3)

In [31]: for index in range(1, 13, 3):


print(index)

for name in ["M1", "M2", "M3", "M4"]:


print(name)

1
4
7
10
M1
M2
M3
M4

In [33]: for index in range(4):


print(index)

0
1
2
3

In [34]: # Function to compute factorial

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 22 of 32
Python_Tutorial 12/01/25, 12:12 PM

def factor(n):
"""
computes the product of all the integers from 1 to n
special case: factor(0) = 1
"""
x = 1
for i in range(n):
print(i)
x = x * (i + 1)
return x

factor(5)
#print(factor(0))
#print(factor(1))
#print(factor(5))
#print(factor(20))

0
1
2
3
4
Out[34]: 120

Vectorization
In [49]: import numpy as np
y = np.zeros(2501)
time = np.zeros(2501)
print(y)
print(len(y))
for i in range(2501):
t = i * 0.02
time[i] = t
y[i] = np.cos(t)
import matplotlib.pyplot as plt
plt.plot(time, y)

[0. 0. 0. ... 0. 0. 0.]


2501
Out[49]: [<matplotlib.lines.Line2D at 0x7fe3f73e49a0>]

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 23 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [44]: print(y)

[1. 0.99980001 0.99920011 ... 0.95370196 0.95952589 0.96496603]

In [35]: y1 = np.zeros(2501)
t = np.arange(0., 50.02, 0.02)
y1 = np.cos(t)
plt.plot(t, y1)

Out[35]: [<matplotlib.lines.Line2D at 0x7fdd1c722850>]

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 24 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [41]: print(y - y1)

[0. 0. 0. ... 0. 0. 0.]

While loop

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 25 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [43]: x = 100
while True:
if x < 0: break
x = x - 5
print(x)

-5

In [44]: x = 100
while x >= 0:
x = x-5
print(x)

-5

In [45]: x = 100
while True:
x = x - 5
if x < 0: break
print(x)

-5

1. continue : terminates the remaining statements in a loop but continues loop


execution

2. break : exits the loop

In [36]: import random


i = 0
sum = 0
while True:
x = random.normalvariate(100, 20)
print('x = ', x)
if x < 100:
#print('xfil = ', x)
continue # skips the rest if random value < 100
i = i + 1
print('x = ', x, 'i = ', i)
sum = sum + x
if i >= 10: break # sums 10 values and exits the loop
avg = sum/i
print(avg)
print(i)

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 26 of 32
Python_Tutorial 12/01/25, 12:12 PM

x = 126.20381360535328
x = 126.20381360535328 i = 1
x = 123.70336483657101
x = 123.70336483657101 i = 2
x = 120.85369259534458
x = 120.85369259534458 i = 3
x = 104.49249930925347
x = 104.49249930925347 i = 4
x = 140.73584980774726
x = 140.73584980774726 i = 5
x = 103.59025400011168
x = 103.59025400011168 i = 6
x = 94.24750480680932
x = 102.18446902325981
x = 102.18446902325981 i = 7
x = 87.32039569615317
x = 108.70383121532561
x = 108.70383121532561 i = 8
x = 85.34851390963848
x = 128.23985572869233
x = 128.23985572869233 i = 9
x = 125.58436154566985
x = 125.58436154566985 i = 10
118.4291991667329
10

Nesting of structures

In [38]: def quadroots(a, b, c):


"""
quadroots: roots of the quadratic equation

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 27 of 32
Python_Tutorial 12/01/25, 12:12 PM

quadroots(a, b, c): real and complex roots of a quadratic polynomial

input:
a = second order coefficient
b = first order coefficient
c = zero order coefficient
output:
r1 = real part of the first root
r2 = real part of the second root
i1 = imaginary part of the first root
i2 = imaginary part of the second root
"""
import math
print(math.sqrt(10))
if a == 0:
# special cases
if b != 0:
r1 = -c/b
return r1
else:
# trivial solution
print("Trivial solution. Try again")
else:
# quadratic formula
d = b**2 - 4*a*c
if d >= 0:
# real roots
print(d)
r1 = (-b + math.sqrt(d))/(2*a)
r2 = (-b - math.sqrt(d))/(2*a)
i1 = 0
i2 = 0
else:
# complex roots
r1 = -b/(2*a)
r2 = r1
i1 = math.sqrt(abs(d))/(2*a)
i2 = -math.sqrt(abs(d))/(2*a)
return r1, i1, r2, i2

In [41]: quadroots(1, 4, 1)

3.1622776601683795
12
Out[41]: (-0.2679491924311228, 0, -3.732050807568877, 0)

In [53]: import math


math.sqrt(10)

Out[53]: 3.1622776601683795

Lambda functions
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 28 of 32
Python_Tutorial 12/01/25, 12:12 PM

In [56]: f1 = lambda x, y: x**2 + y**2


f1(3, 4)

Out[56]: 25

Can include variables from workspace.

In [57]: a = 4; b = 2
f2 = lambda x: a*x**b
f2(3)

Out[57]: 36

Python functions with function names as arguments

In [59]: import numpy as np


def midpoint(f, x1, x2):
"""
this function evaluates f(x) at the midpoint between x1 and x2
"""
xmid = (x1 + x2)/2
return (f(xmid))

def f(w):
return np.sin(w)*np.cosh(w) - 5

fmid = midpoint(f, 0, 3)
print('function value at midpoint = ', fmid)

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 29 of 32
Python_Tutorial 12/01/25, 12:12 PM

function value at midpoint = -2.6534832023556882

In [60]: g = lambda x: np.pi*x**2/4


midpoint(g, 1.5, 2.78)

Out[60]: 3.596809429094953

Passing parameters to functions-1


In [44]: import numpy as np
def func(t, m = 70, cd = 0.25): # default values of m and cd are given
g = 9.81
f = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*t)
return f

print(func(12, cd=0.3))
print(func(12, m=100)) # disregards third argument
print(func(12, 70, 0.25))
print(func(12))
print(func(12, 0.25))

47.15084308112941
59.78698843813102
51.24944572226363
51.24944572226363
3.132091952673165

In [65]: print(func(12, 70, 0.25))


print(func(12, m=70))
print(func(12, cd=0.25))
print(func(12, 70))

51.24944572226363
51.24944572226363
51.24944572226363
51.24944572226363
3.0688108446106614

Passing parameters to function-2


In [45]: import numpy as np
def funcavg(f, a, b, n, *args):
"""
computes the average of a function
over a range
requires import of numpy module
input:
f = function to be evaluated
a = lower bound of range
b = upper bound of range
n = number of intervals

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 30 of 32
Python_Tutorial 12/01/25, 12:12 PM

output:
favg = average value of the function
"""
x = np.linspace(a, b, n)
y = f(x, *args)
favg = np.average(y)
return favg

def func(t, m, cd): # note that m, cd become *args


g = 9.81
f = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*t)
return f

a = 0; b = 12; n = 60; m = 68.1; cd = 0.25


favg = funcavg(func, a, b, n, m, cd) # m, cd, gets passed via *args
print('{0:7.3f}'.format(favg))

36.013

Below we use it with kwargs

In [6]: import numpy as np


def funcavg(f, a, b, n, **kwargs):
"""
computes the average of a function
over a range
requires import of numpy module
input:
f = function to be evaluated
a = lower bound of range
b = upper bound of range
n = number of intervals

output:
favg = average value of the function
"""
x = np.linspace(a, b, n)
y = f(x, **kwargs)
favg = np.average(y)
return favg

def func(t, m=70, cd=0.25): # note that m, cd become **kwargs to be actually ty


g = 9.81
f = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*t)
return f

a = 0; b = 12; n = 60; m = 68.1; cd = 0.25


favg = funcavg(func, a, b, n, m=m, cd=cd) # m, cd, gets passed via **kwargs
print('{0:7.3f}'.format(favg))

36.013

For a more detailed discussion on args and kwargs see the following link.

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 31 of 32
Python_Tutorial 12/01/25, 12:12 PM

This finishes the basic tutorial on Python programming. For a more thorough
discussion take a look at any of the references provided on BodhiTree. Below is an
example for combined

In [69]: import numpy as np


def funcavg(f, a, b, n, *args, **kwargs):
"""
computes the average of a function
over a range
requires import of numpy module
input:
f = function to be evaluated
a = lower bound of range
b = upper bound of range
n = number of intervals

output:
favg = average value of the function
"""
x = np.linspace(a, b, n)
y = f(x, *args, **kwargs)
favg = np.average(y)
return favg

def func(t, m, cd=0.25): # note that m, cd become **kwargs to be actually typed


g = 9.81
f = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*t)
return f

a = 0; b = 12; n = 60; m = 68.1; cd = 0.25


favg = funcavg(func, a, b, n, m, cd=cd) # m: passed via args; cd: passed via **
print('{0:7.3f}'.format(favg))

36.013

The scope of the language is vast. Learn more using the resources that I have
provided. You can also use one of the AI tools to write to code or debug it.

In [ ]:

http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 32 of 32

You might also like