Saturday, February 25, 2017
Designing Smart Macros
Like a scribe in ancient Egypt a programmer has to be prepared to handle seemingly impossible tasks. One can be ultra cautious and try to handle all possible exceptions but the price of that is a reduction in efficiency resulting in increased computing times. However not catching an error can cause processing to be halted and everything done prior to that is lost. So a compromise might be to run a simple test that will handle most cases and use a more sophisticated procedure to handle rarer cases.
In Excel the complex numbers are stored as strings. An imround macro that would round a complex number to a fixed number of decimal places could be programmed to check to first see if the selected cell contained a string and abort operation is it doesn't. One could then check to see if the string is of the form x+yi where x and y are decimal numbers. But complex numbers can also be written in scientific or engineering format where exponentials occur. Numbers like 1/2+2/3i are also complex numbers but this is more like a formula and we can exclude it from the range of possibilities that the macro has to act on. I was able to create a smarter version of my original imround macro that could handle simple complex numbers and ignore anything else that might be contained in a cell. It's a fail safe strategy.
Note that the result of a rounding operation may not necessarily be a complex number. Above 1.+0.i is rounded to 1. It might be wise for computer programs to be designed in such a way that they have a known area of competence and avoid acting outside it.