Using the MOD function as a debugging tool


I showed a SAS/IML customer a debugging tip, and she said that I should blog about it because she had never seen it before. The tip is very simple: inside of a DO loop, use the MOD function to selectively print the values of variables.

Recall that the expression MOD(a,b) is zero when a is a multiple of b. Suppose that you have a DO loop that iterates from 1 to 100. You can do something every 10 iterations by using the MOD function, as follows:

proc iml;
do i = 1 to 100;
   x = sum(1:i);
   if mod(i,10)=0 then do; /* print every 10 iterations */
      print i x;

The example prints the values of x for when i equals 10, 20,..., 100. In a real program, you might want to print the current state of an iterative algorithm such as Newton's method to view partial results and determine whether the algorithm is converging.

This technique can be useful for debugging iterative algorithms, or for limiting the amount of output in the loop of a long-running program.


About Author

Rick Wicklin

Distinguished Researcher in Computational Statistics

Rick Wicklin, PhD, is a distinguished researcher in computational statistics at SAS and is a principal developer of SAS/IML software. His areas of expertise include computational statistics, simulation, statistical graphics, and modern methods in statistical data analysis. Rick is author of the books Statistical Programming with SAS/IML Software and Simulating Data with SAS.


  1. I am trying to do some maximum likelihood estimation. The optimizer I am using - NLPQN - is bombing out. I suspect there is a problem with my likelihood function where some particular parameter values are causing it to return missing values.

    Is there a way to spit out the parameter vector and other information from inside the likelihood function i've coded as a module. When I try to, print output the optimizer also bombs out.


Leave A Reply

Back to Top