views:

364

answers:

5

So according to cplusplus.com when you set the format flag of an output stream to scientific notation via

of.setf(ios::scientific)

you should see 3 digits plus and a sign in the exponent. However, I only seem to get 2 in my output. Any ideas? Compiled on Mac OS using GCC 4.0.1.

Here's the actual code I am using:

of.setf(ios::scientific);
of.precision(6);
for (int i=0;i<dims[0];++i) {
    for (int j=0;j<dims[1];++j) {
 of << setw(15) << data[i*dims[1]+j];     
    }
    of << endl;
}

and an example line of output:

   1.015037e+00   1.015037e+00   1.395640e-06  -1.119544e-06  -8.333264e-07

Thanks

+1  A: 

I believe cplusplus.com is incorrect, or at least is documenting a particular implementation - I can't see any other online docs which specifically state the number of exponent digits which are displayed - I can't even find it in the C++ specification.

Edit:

The C++ Standard Library: A Tutorial and Reference doesn't explicitly state the number of exponent digits; but all it's examples display two exponent digits.

Dave Rigby
+2  A: 

It's implementation specific.

Martin Beckett
A: 

I'm getting 3 in MSVC++08 and g++ 4.4.0 with this code:

#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <vector>

typedef float NumberType;

double generate_number(void)
{
    return static_cast<NumberType>(std::rand()) / RAND_MAX;
}

void print_number(NumberType d)
{
    std::cout << std::setw(15) << d << std::endl;
};

int main(void)
{
    std::vector<NumberType> data;

    std::generate_n(std::back_inserter(data), 10, generate_number);

    // print
    std::cout.setf(std::ios::scientific);
    std::cout.precision(6);
    std::for_each(data.begin(), data.end(), print_number);
}

You can easily change the number type it uses. It gives me three places with both float and double, and the standard says nothing on the actual formatting, so I'd go with mgb's answer.

GMan
Same code compiled on OS X/Intel gives two exponent digits - looks pretty conclusive it's simply implementation-dependent.
Dave Rigby
Indeed, you beat my edited-to-conclusion by a minute. :)
GMan
@GMan: Always the way on SO ;)
Dave Rigby
A: 

I have just had a thought - since I am printing floats, why would it display 3 exponent values since the max/min exponent is ~38. I bet if the data array were type double there would be 3. Thanks for the answer though Dave.

Ian Buss
A: 

This is a bug in M$ implementation AFAIK

http://groups.google.com/group/comp.lang.c++/browse%5Fthread/thread/624b679a4faf03d

malat