Python Lecture 17-NumericalComputing
Python Lecture 17-NumericalComputing
• Computing a definite
integral y = f(x)
• Integral of f(x) between
x=a and x=b is the
area under the curve
y=f(x) between x=a
and b
x=a x=b
• This area can be
approximated
numerically
Courtesy Prof PR Panda CSE Department IIT Dehi
Rectangular Rule
y = f(x)
• Divide interval [a,b] into n
equal sub-intervals
– length of sub-interval
h=(b-a)/n
• In each interval,
approximate f(x) by f(x*)
– f(x*) is the value of f(x) at the x=a x=b
mid-point x*of the interval x=a
• Areas of the rectangles are
h.f(x1*), h.f(x2*),...,h.f(xn*) x1* x2* xn*
• f is approximated by a
step-function def f(x): ….
• This will work no matter
def integrate_midpoint(f,a,b,n):
how complex f is h = (b-a)/n
• Accuracy depends on n x = a + h/2
– trade-off against sum = 0.0
computation time for i in range(n):
sum += f(x)
• Only definite integral, no x += h
indefinite integral using return sum*h
this method
Courtesy Prof PR Panda CSE Department IIT Dehi
Trapezoidal Rule
• Example
https://www.southampton.ac.uk/~fangohr/training/python/pdfs/Python-for-Computational-Science-and-Engineering.pdf
Trapezoidal Rule
• Simple rule
https://www.southampton.ac.uk/~fangohr/training/python/pdfs/Python-for-Computational-Science-and-Engineering.pdf
Trapezoidal Rule
• Example
https://www.southampton.ac.uk/~fangohr/training/python/pdfs/Python-for-Computational-Science-and-Engineering.pdf
Trapezoidal Rule
• Composite Rule
https://www.southampton.ac.uk/~fangohr/training/python/pdfs/Python-for-Computational-Science-and-Engineering.pdf
Trapezoidal Rule
• Divide interval [a,b] into n
equal sub-intervals
y = f(x)
– length of sub-interval
h=(b-a)/n
• In each interval,
approximate f(x) by line
segments with end-points:
– [a,f(a)], [x1,f(x1)],..., [b,f(b)]
• Areas of the trapeziums
are x=a x=b
– 1/2 h (f(a) + f(x1)),
– 1/2 h (f(x1) + f(x2)),...,
– 1/2 h (f(xn-1) + f(b)) x1 x2 xn-1
x3 x2 x1 x0
Courtesy Prof PR Panda CSE Department IIT Dehi
Program for Newton-Raphson
Method
• Convergence def f(x):
detected if def fp(x):
new_guess is less
than err away from def newton(x0, f, fp, error, n):
guess = x0
guess for i in range(n):
d = fp(guess)
• Fails if tangent slope if d == 0: print('There is an error')
is zero else:
new_guess = guess-f(guess)/d
• Signal failure if no if abs(new_guess - guess) < error:
convergence after N print('successful')
iterations return new_guess
guess = new_guess
– if failure, try again print('failed')
with different x0 return 0