Friday, May 6, 2011

What is the C++ function to raise a number to a power?

How do I raise a number to a power?

2^1

2^2

2^3

etc...

From stackoverflow
  • pow() in the cmath library. More info here.

    Nils Pipenbrinck : hell, yes.. it's really that simple..
    Joey Robert : Easy reputation.
  • pow

  • Use the pow(x,y) function: See Here

    Just include math.h and you're all set.

  • It's pow or powf in <math.h>

    There is no special infix operator like in Visual Basic or Python

    newacct : powf() is a C99 function that is not in C++.
  • pow(2.0,1.0)
    pow(2.0,2.0)
    pow(2.0,3.0)
    

    Your original question title is misleading. To just square, use 2*2.

  • You should be able to use normal C methods in math.

    #include <cmath>

    pow(2,3)

    if you're on a unix-like system, man cmath

    Is that what you're asking?

    Sujal

  • While pow( base, exp ) is a great suggestion, be aware that it typically works in floating-point.

    This may or may not be what you want: on some systems a simple loop multiplying on an accumulator will be faster for integer types.

    And for square specifically, you might as well just multiply the numbers together yourself, floating-point or integer; it's not really a decrease in readability (IMHO) and you avoid the performance overhead of a function call.

    leander : And yeah, this may fall into the "premature optimization" category, but I always find it good to be aware of things like this -- especially if you have to program in limited-resource environments.
  • Some lawyer crap from me again. I've often fallen in this pitfall myself, so i'm going to warn you about it. std::pow in the <cmath> header has these overloads:

    pow(float, float);
    pow(float, int);
    pow(double, double); // taken over from C
    pow(double, int);
    pow(long double, long double);
    pow(long double, int);
    

    Now you can't just do

    pow(2, N)
    

    with N being an int, because it doesn't know which of float, double or long double version it should take, and you would get an ambiguity error. All three would need a conversion from int to floating point, and all three are equally costly!

    Therefor, be sure to have the first argument typed so it matches one of those three perfectly. I usually use double

    pow(2.0, N)
    
  • I think, if you use the way which you know, it will be better.. here it is..

    #include <math.h>
    
    
    struct float_t
    {
    
        float value;
    
        float_t(float v)
        {
         value = v;
        }
        operator float()
        {
         return value;
        }
        float operator ^(float c)
        {
         return powf(value, c);
        }
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
        float_t num(4);
        printf("%f", num ^ 3);
    }
    

0 comments:

Post a Comment