# Preventing Divide by Zero Errors

**QUESTION:** I'm dividing one array by another in IDL, but occasionally the divisor array
contains zeros. This, of course, causes a divide by zero error and a positive or negative infinity (INF)
to be inserted in the result array. Is there an elegant way to code this up to prevent this sort of thing?

** ANSWER:** *Mais oui!* Ed Meinel has pointed this out to me on more than
a couple of occasions. Here is his solution for integers (represented as floating arrays,
if you want to do floating point arithmetic, of course). The variable *replacement_value*
represents whatever value you think is appropriate in the circumstances. Something like 1e-6
often works fine.

IDL> c = a / (b + replacement_value * (b EQ 0))

For floating point values, where the number zero cannot be assumed to be exactly zero, Jean Hasban suggests this variation,

IDL> c = a / (b + replacement_value * (ABS(b) LT epsilon))

where *epsilon *is usually taken to be something like the smallest number that
can be represented on your computer, or:

IDL> epsilon = (Machar()).eps IDL> Print, epsilon 1.19209e-007

Other users just prefer to get the error. Then, at least they know what is going on.

*Version of IDL used to prepare this article: IDL 7.0.1.*

Copyright © 2008 David W. Fanning

Last Updated 22 May 2008