Page - 202 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 202 -
Text of the Page - 202 -
202 6 SolvingNonlinearAlgebraicEquations
while abs(f_value) > eps and iteration_counter < 100:
try:
x = x - float(f_value)/dfdx(x)
except ZeroDivisionError:
print "Error! - derivative zero for x = ", x
sys.exit(1) # Abort with error
f_value = f(x)
iteration_counter += 1
if return_x_list:
x_list.append(x)
# Here, either a solution is found, or too many iterations
if abs(f_value) > eps:
iteration_counter = -1 # i.e., lack of convergence
if return_x_list:
return x_list, iteration_counter
else:
return x, iteration_counter
The function is found in thefilenonlinear_solvers.py.
Wecannowmakeacall
x, iter = Newton(f, dfdx, x=1000, eps=1e-6, return_x_list=True)
andget a listx returned. With knowledgeof the exact solutionx off.x/ D 0
wecancompute all the errorsen andall the associatedqn valueswith the compact
function
def rate(x, x_exact):
e = [abs(x_ - x_exact) for x_ in x]
q = [log(e[n+1]/e[n])/log(e[n]/e[n-1])
for n in range(1, len(e)-1, 1)]
return q
The errormodel (6.5)workswell forNewton’smethod and the secantmethod.
For thebisectionmethod,however, itworkswell in thebeginning,butnotwhen the
solution is approached.
Wecancompute the ratesqn andprint themnicely,
def print_rates(method, x, x_exact):
q = [’%.2f’ % q_ for q_ in rate(x, x_exact)]
print method + ’:’
for q_ in q:
print q_,
print
The result forprint_rates(’Newton’, x, 3) is
Newton:
1.01 1.02 1.03 1.07 1.14 1.27 1.51 1.80 1.97 2.00
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