Page - 195 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 195 -
Text of the Page - 195 -
6.2 Newton’sMethod 195
except ZeroDivisionError:
print "Error! - derivative zero for x = ", x
sys.exit(1) # Abort with error
f_value = f(x)
iteration_counter += 1
# Here, either a solution is found, or too many iterations
if abs(f_value) > eps:
iteration_counter = -1
return x, iteration_counter
def f(x):
return x**2 - 9
def dfdx(x):
return 2*x
solution, no_iterations = Newton(f, dfdx, x=1000, eps=1.0e-6)
if no_iterations > 0: # Solution found
print "Number of function calls: %d" % (1 + 2*no_iterations)
print "A solution is: %f" % (solution)
else:
print "Solution not found!"
Handlingofthepotentialdivisionbyzeroisdonebyatry-exceptconstruction.
Python tries to run thecode in thetryblock. Ifanythinggoeswronghere,ormore
precisely, if Python raises an exception caused by a problem (such as division by
zero,arrayindexoutofbounds,useofundefinedvariable,etc.), theexecutionjumps
immediately to theexceptblock. Here, the programmer can take appropriate ac-
tions. In thepresent case,we simply stop theprogram. (Professional programmers
would avoid callingsys.exit inside a function. Instead, theywould raise a new
exceptionwith an informativeerrormessage, and let the callingcodehaveanother
try-exceptconstruction tostop theprogram.)
The division by zerowill always be detected and the programwill be stopped.
Themain purpose of our way of treating the division by zero is to give the user
amore informativeerrormessageandstop theprograminagentlerway.
Calling sys.exitwith an argument different from zero (here 1) signifies that
the programstopped because of an error. It is a goodhabit to supply the value1,
because tools in theoperatingsystemcan thenbeusedbyotherprograms todetect
thatourprogramfailed.
To prevent an infinite loop because of divergent iterations, we have introduced
theintegervariableiteration_countertocountthenumberof iterations inNew-
ton’smethod.Withiteration_counterwecaneasilyextendthecondition in the
whilesuchthatnomoreiterations takeplacewhenthenumberof iterationsreaches
100.Wecouldeasily let this limitbeanargumentto thefunctionrather thanafixed
constant.
TheNewton function returns the approximate solutionand thenumberof itera-
tions. The latter equals 1 if theconvergencecriterion jf.x/j< wasnot reached
within themaximum number of iterations. In the calling code, we print out the
back to the
book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik