Loading [MathJax]/extensions/tex2jax.js

Tuesday, October 11, 2011

Avoid possible division by zero by limiting the divisor

The friendly "division by zero" warning has appeared to almost anyone that had a pocket calculator. Although this can be a nice greeting from our little digital friends that is bidding us to give it some more though on our problem and the required computations, it is generally a pain if one has a large code and has to wait several hours, if not days, to finish a computation. It is sometimes natural that in the progress of the numerical steps needed to solve a PDE where the initial and some boundary conditions are dubious, that the solution needs to wander a bit before giving up and returning those anxiously awaited results.

So, for an operation "a/b" where "b" is may be 0 at some point, a limiter can be applied such that a minimum threshold, dictated by parameter "SMALL", forces the value to be higher than zero and also to avoid underflows.

REAL, PARAMETER :: SMALL = 1.E-18
!! for a divisor b>0
c = a/MAX(b, SMALL)
!! for a divisor b with an arbitrary sign
c = a/SIGN(MAX(ABS(b), SMALL), b)
view raw gistfile1.f90 hosted with ❤ by GitHub

No comments:

Post a Comment