Introduction to
Numerical
Fundamentals
Dr. Cem Özdo
˘
gan
LOGIK
Numerical
Fundamentals
Analysis vs Numerical
Analysis
Some disasters attributable
to bad numerical computing
Floating-Point Arithmetic
Computer Number
Representation
Kinds of Errors in Numerical
Procedures
Absolute vs Relative Error
& Convergence
3.22
Absolute vs Relative Error & C onvergence II
1 def n ewtsqrt ( x , delt a , maxit ) :
2 r = x / 2 ; r o l d = x # I n i t i a l i z e , make sure convergence t e s t f a i l s on f i r s t t r y
3 i t = 0
4 w h i l e ( r ! = r o l d ) and ( i t < maxit ) : # Convergence t e s t
5 # while ( ( r−r o l d ) > d e lt a ) and ( i t <maxit ) : # Convergence te s t
6 # while ( abs ( r−rol d ) > de l t a ) and ( i t <maxit ) : # Convergence t e s t
7 # while ( abs ( ( r−ro l d ) / r o l d ) > d e l t a ) and ( i t <m axit ) : # Convergence te s t
8 r o l d = r # Save ol d valu e f o r next convergence t e s t
9 r = 0 . 5
*
( r o l d + x / r o l d ) # Upda te the guess
10 i t = i t + 1
11 r e t u r n r
12 # Tes t the newtsqrt f u n c t i o n f o r a range o f in p u t s
13 x t e s t = [4 , 0.04 , 4e−4, 4e−6, 4e−8, 4e−10, 4e−12] # arguments t o t e s t
14 p r i n t ( " Absolute Converg ence C r i t e r i o n " )
15 p r i n t ( " x s q r t ( x ) new t s qrt ( x ) e r r o r r e l e r r " )
16 i m p o r t math
17 f o r x i n xt e s t : # repe a t f o r each element in x t e s t
18 r = math . s q r t ( x )
19 r n = n e wt s qrt ( x , 5 e−9,25)
20 er r = abs ( rn − r )
21 r e l e r r = er r / r
22 p r i n t ( " %10.3e %10.3e %10.3e %10.3e %10.3e " % ( x , r , rn , err , r e le r r ) )
Figure: Output of newtsqrt.py
Newton’s method to
compute the square root
of a number.
Example py-file:
newtsqrt.py