Tuesday, May 3, 2011

decimal places and Pow function in c++

Most likely a really simple question, please keep any answers easy to understand I'm still quite new at this:

I'm making a little app, and I need to use powers for a couple of calculations. After a little research I found the pow function in cmath, and have had a play. In the end i came up with this snipped, which works:

#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
    float dummy2, test(6.65);
    dummy2 = (float) pow((float) 3.57, test);
    cout << dummy2;

    return 0; 
}

and it returns the correct answer (4734.17), but only to two decimal places. I want 5 decimal places preferably.

What did I do wrong here? Am I using the wrong data type (floats)? Or is it a limit of whatever is in the pow function to using only 2dp?

I could, if it came to it just define constants with the values i want, since it's only going to be 4 or 5 sums that I need this precision on, but if it's possible to have the program calculate it that would be great.

Thanks

From stackoverflow
  • For a better precision you should use double. Doubles has 15 digits of precision against 7 for floats.

    dmckee : 15 and 7 decimal digits are only rough values. In particular, 7 for floats may be a little optimistic...
  • Google is your friend. These results and these as well have what you want, namely that you need to use setprecision() as a cout parameter.

    Dmatig : Oh excellent thank you! It never even crossed my mind to think it might be a cout thing, i just assumed it was part of the pow function. Seems so obvious now! Much appreciated.
  • I would do as fbinder says, and use Doubles for greater precision. To solve your problem, you have two options, C-style and C++ style.

    C-Style

    #include <cstdio>
    printf("%.5f", dummy2);
    

    C++ Style

    #include <iomanip>
    std::cout << setprecision(5) << dummy2 << std::endl;
    

    OR

    std::cout.precision(5);
    std::cout << dummy2 << std::endl;
    // continue to use cout to output 5 decimal places
    

0 comments:

Post a Comment