The more you understand bugs, the better you will be at debugging. There are four kinds of bugs:
You have written a command that cannot execute because it violates one of the language’s syntax rules. For example, in MATLAB, you can’t have two operands in a row without an operator, so
pi r^2 contains a syntax error. When the interpreter finds a syntax error, it prints an error message and stops running your program.
Your program starts running, but something goes wrong along the way. For example, if you try to access a variable that doesn’t exist, that’s a runtime error. When the interpreter detects the problem, it prints an error message and stops.
Your program runs without generating any error messages, but it doesn’t do the right thing. The problem in the previous section, where we changed the value of
b before reading the old value, is a logical error.
Most computations in MATLAB are only approximately right. Most of the time the errors are small enough that we don’t care, but in some cases the round-off errors are a problem.
Syntax errors are usually the easiest to deal with. Sometimes the error messages are confusing, but MATLAB can usually tell you where the error is, at least roughly.
Runtime errors are harder because, as I mentioned before, MATLAB can tell you where it detected the problem, but not what caused it.
Logical errors are hard because MATLAB can’t help at all. From MATLAB’s point of view there’s nothing wrong with the program; only you know what the program is supposed to do, so only you can check it.
Numerical errors can be tricky because it’s not clear whether the problem is your fault. For most simple computations, MATLAB produces the floating-point value that is closest to the exact solution, which means that the first 15 significant digits should be correct.
But some computations are ill-conditioned, which means that even if your program is correct, the round-off errors accumulate and the number of correct digits can be smaller. Sometimes MATLAB can warn you that this is happening, but not always! Precision (the number of digits in the answer) does not imply accuracy (the number of digits that are right).