views:

119

answers:

3

I'm using c++ in visual studio express to generate random expression trees for use in a genetic algorithm type of program.

Because they are random, the trees often generate: divide by zero, overflow, underflow as well as returning "inf" and other strings. I can write handlers for the strings, but the literature left me baffled about the others. If I understand it correctly, I have to set some flags first?

Advice and/or a pointer to some literature would be appreciated. Edit: the values returned in the double variable are 1.#INF or -1.#IND. I was wrong to call them strings.

A: 

Never tried it, but assuming divide by zero throws an exception, you could just wrap the code in a try/catch like this:

try { // potential divide by zero... } catch(...) { // ... catches ALL exceptions }

Sophtware
That's wrong, because the C++ runtime environment won't help you here. It won't throw an exception for any reason other than what the programmer specifically asked to throw for.
wilhelmtell
+2  A: 

The C++ runtime environment won't help you the slightest here. You have to perform these checks yourself, explicitly in your code. Unless of course the functions you're calling are doing these checks -- in which case it depends on how they behave in the case of an error.

Let me explain:

double divide(double a, double b) {
    return a / b;  // undefined if b is zero
}

Should be in fact

double divide(double a, double b) {
    if( b == 0 ) {
        // throw, return, flag, ...  you choose how to signal the error
    }
    return a / b;  // b can't possibly be zero here
}

If the code that fails on divide-by-zero and such isn't yours then you'll have to dig deeper to find what it does in the case of a threat for an error. Does it throw? Set a flag? Ask the author and/or read the source.

Here's an example for an exception:

struct bad_value : public std::exception { };

double divide(double a, double b) {
    if( b == 0 ) throw bad_value("Division by zero in divide()");
    return a / b;  // b can't possibly be zero here
}

// elsewhere (possibly in a parallel universe) ...

    try {
        double r1 = divide(5,4);
        double r2 = divide(5,0);
    } catch( bad_value e ) {
        // ...
    }
wilhelmtell
Thanks. It looks like I'll have to implement my own 'throw's.
Peter Stewart
+3  A: 

Are you sure you want to catch them instead of just ignoring them? Assuming you just want to ignore them:

See this: http://msdn.microsoft.com/en-us/library/c9676k6h.aspx

For the _MCW_EM mask, clearing the mask sets the exception, which allows the hardware exception; setting the mask hides the exception.

So you're going to want to do something like this:

#include <float.h>
#pragma fenv_access (on)

void main()
{
    unsigned int fp_control_word;
    unsigned int new_fp_control_word;

    _controlfp_s(&fp_control_word, 0, 0);

    // Make the new fp env same as the old one,
    // except for the changes we're going to make
    new_fp_control_word = fp_control_word | _EM_INVALID | _EM_DENORMAL | _EM_ZERODIVIDE | _EM_OVERFLOW | _EM_UNDERFLOW | _EM_INEXACT;
    //Update the control word with our changes
    _controlfp_s(&fp_control_word, new_fp_control_word, _MCW_EM)


}

Some of the confusion here may be over the use of the word "exception". In C++, that's usually referring to the language built-in exception handling system. Floating point exceptions are a different beast altogether. The exceptions a standard FPU is required to support are all defined in IEEE-754. These happen inside the floating-point unit, which can do different things depending on how the float-point unit's control flags are set up. Usually one of two things happens: 1) The exception is ignored and the FPU sets a flag indicating an error occurred in its status register(s). 2) The exception isn't ignored by the FPU, so instead an interrupt gets generated, and whatever interrupt handler was set up for floating-point errors gets called. Usually this does something nice for you like causing you to break at that line of code in the debugger or generating a core file.

You can find more on IEE-754 here: http://www.openwatcom.org/ftp/devel/docs/ieee-754.pdf

Some additional floating-point references: http://docs.sun.com/source/806-3568/ncg_goldberg.html http://floating-point-gui.de/

George
Assuming the code is running on an x86 processor...
dthorpe
dthorpe: actually, I'm not assuming that it is running on an x86 processor. The MSDN docs explicitly state that _controlfp_s is the new "platform independent" way to do this. I suspect by platform independent they're referring to CPU type, as obviously not all x86 operating systems have this function - as long as he's doing this on a windows platform, he should be OK.
George
Also be aware that I've seen libraries warring over the setting of the floating-point control word, each imposing its preference on the other. Almost as bad as printer drivers changing the locale under a program's feed...
Donal Fellows
@George: what a great answer! The references were very interesting. You're right, I just want to ignore them. I'll check if the answer is within my acceptable range and throw my own exception if it isn't. The flags are good to know about. Thanks.
Peter Stewart
@Peter Stewart: One important thing to keep in mind with your answers is if you get a NaN (Not a Number) as a result, comparison operators don't work the way you think they'll work. For example, one easy way to detect whether a result is a NaN is by checking to see if "f != f" returns true. You might want to check that as well.See this question:http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c
George
@George: thanks. I'll note that.
Peter Stewart