|Writing DEG/RAD mode-insensitive code|
Message #1 Posted by Stefan Vorkoetter on 20 Aug 2007, 12:34 p.m.
A lot of times, I see programs that depend on the calculator's angle mode being set in a particular way. Or, the program sets the angle mode based on what it needs. I gave some thought as to how to write programs that do trig, but don't depend on the angle mode being set properly. Two approaches came to mind:
1. Determine the angle mode at program start, change it as needed, and then change it back upon completion.
2. Determine the angle mode at program start, and then do conversions as necessary during processing.
Suppose we want to write a program that works in degrees (such as an aviation related program). First let's look at option 1:
Determining the angle mode is easy. We can then use a flag to remember what it is. The following sequence of instructions determines the angle mode, and sets flag 0 if it is radians. Then it sets the mode to degrees:
To restore the initial angle mode later, we just need to do:
For option 2, we use the same initial sequence as option 1, except we omit the DEG instruction at the end.
Then, just before any function that expects an angle as an argument, we do:
After any function that returns an angle, we do:
At the end of the program, there's nothing to do, since we didn't change the calculator's angle mode setting at all (although we could clear the flag just to clean things up).
Of course, using this method trades making one change to the calculator's state (the angle mode) for a different change (the setting of a flag), but the latter is probably less likely to interfere with something.