Introduction to Programming with Mathematica, Third Edition

Appendix B: Debugging

Overview

Whenever you write programs, much of your time will be spent in debugging figuring out why your program does not work. In this appendix, we offer a few tips on debugging, and also give some examples of common programming errors.

Tracing evaluation

In any programming language, the programmer will, at some point, be faced with an unexpected, and perhaps, mysterious result. You might be expecting one output, but an entirely different one is generated. Or your program may not run to completion and only give error or warning messages that are difficult to decipher. In such situations, you may find it helpful to take a peek at Mathematica's evaluation process. This is most easily done with Trace and related functions. For example, using Trace on a simple arithmetic operation, you can see that Mathematica's evaluator works from the inside out, following the order of operations for arithmetic.

    <i class="emphasis">In[1]:</i>= <b class="bold">Trace [2 (3 + 4 (5 + 6))]</b>    <i class="emphasis">Out[1]</i>= {{{{5 + 6, 11}, 411, 44}, 3 + 44, 47}, 247, 94}

Similarly, tracing the evaluation of an If statement shows that only the first argument to the If function is evaluated initially; the If function itself returns no value, hence the Null at the end of the trace.

    <i class="emphasis">In[2]:</i>= <b class="bold">Trace [If [4 > 9, Print ["true"], Print ["false"]]]</b>    false    Out[2]= {{4...

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: DC-DC Converter Chips
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.