Power function in cpp

Power function in cpp

Returns base raised to the power exponent:

Additional overloads are provided in this header ( ) for other combinations of arithmetic types ( Type1 and Type2 ): These overloads effectively cast its arguments to double before calculations, except if at least one of the arguments is of type long double (in which case both are casted to long double instead).

This function is also overloaded in and (see complex pow and valarray pow).

Parameters

Return Value

The result of raising base to the power exponent .

If the base is finite negative and the exponent is finite but not an integer value, it causes a domain error.
If both base and exponent are zero, it may also cause a domain error on certain implementations.
If base is zero and exponent is negative, it may cause a domain error or a pole error (or none, depending on the library implementation).
The function may also cause a range error if the result is too great or too small to be represented by a value of the return type.

If a domain error occurs, the global variable errno is set to EDOM .
If a pole or range error occurs, the global variable errno is set ERANGE .

If a domain error occurs:
— And math_errhandling has MATH_ERRNO set: the global variable errno is set to EDOM .
— And math_errhandling has MATH_ERREXCEPT set: FE_INVALID is raised.

Читайте также:  Python replace text regexp

If a pole error occurs:
— And math_errhandling has MATH_ERRNO set: the global variable errno is set to ERANGE .
— And math_errhandling has MATH_ERREXCEPT set: FE_DIVBYZERO is raised.

If a range error occurs:
— And math_errhandling has MATH_ERRNO set: the global variable errno is set to ERANGE .
— And math_errhandling has MATH_ERREXCEPT set: either FE_OVERFLOW or FE_UNDERFLOW is raised.

Example

/* pow example */ /* printf */ /* pow */ int main () < printf ("7 ^ 3 = %f\n", pow (7.0, 3.0) ); printf ("4.73 ^ 12 = %f\n", pow (4.73, 12.0) ); printf ("32.01 ^ 1.54 = %f\n", pow (32.01, 1.54) ); return 0; >
 7 ^ 3 = 343.000000 4.73 ^ 12 = 125410439.217423 32.01 ^ 1.54 = 208.036691 

See also

log Compute natural logarithm (function) exp Compute exponential function (function) sqrt Compute square root (function)

Источник

pow , powf , powl

Вычисляет значение x , возведенное в степень y .

Синтаксис

double pow( double x, double y ); float powf( float x, float y ); long double powl( long double x, long double y ); define pow(X, Y) // Requires C11 or higher double pow( double x, int y ); // C++ only float pow( float x, float y ); // C++ only float pow( float x, int y ); // C++ only long double pow( long double x, long double y ); // C++ only long double pow( long double x, int y ); // C++ only 

Параметры

Возвращаемое значение

Возвращает значение . x y Сообщение об ошибке не выводится в случае переполнения или потери значимости.

x Значения и y Возвращаемое значение pow
x != 0,0 и y == 0,0 1
x == 0,0 и y == 0,0 1
x == 0,0 и y < 0 INF

Комментарии

pow не распознает целочисленные значения с плавающей запятой больше 2 64 (например, 1.0E100).

Функция pow содержит реализацию, которая использует Streaming SIMD Extensions 2 (SSE2). Сведения и ограничения по использованию реализации SSE2 см. в разделе _set_SSE2_enable .

Так как C++ допускает перегрузку, можно вызывать любые перегрузки pow . В программе C, если вы не используете макрос для вызова этой функции, pow всегда принимает два double значения и возвращает double значение.

Если вы используете pow макрос из , тип аргумента определяет, какая версия функции выбрана. Дополнительные сведения см. в разделе Типообразная математика .

Перегрузка pow(int, int) более не доступна. Если вы используете эту перегрузку, компилятор может выдавать C2668. Чтобы избежать этой проблемы, необходимо привести параметр к типу double , float или long double .

Первоначально перегрузки pow(T, int) раскрутили pow вызов в последовательность встроенных операций умножения. Хотя он был быстрее, он также был гораздо менее точным. Эта реализация была удалена в Visual Studio 2015 с обновлением 1. Дополнительные сведения см. в статье Улучшения соответствия в Visual Studio 2015 с обновлением 1.

По умолчанию глобальное состояние этой функции ограничивается приложением. Чтобы изменить это поведение, см. статью Глобальное состояние в CRT.

Требования

Подпрограмма Обязательный заголовок (C) Обязательный заголовок (C++)
pow , powf , powl или
pow Макрос

Дополнительные сведения о совместимости см. в разделе Compatibility.

Пример

// crt_pow.c #include #include int main( void )
2.0 to the power of 3.0 is 8.0 

Источник

std:: pow, std:: powf, std:: powl

1-4) Computes the value of base raised to the power exp . The library provides overloads of std::pow for all cv-unqualified floating-point types as the type of the parameters base and exp . (since C++23)

Contents

[edit] Parameters

[edit] Return value

If no errors occur, base raised to the power of exp ( base exp
), is returned.

If a domain error occurs, an implementation-defined value is returned (NaN where supported).

If a pole error or a range error due to overflow occurs, ±HUGE_VAL , ±HUGE_VALF , or ±HUGE_VALL is returned.

If a range error occurs due to underflow, the correct result (after rounding) is returned.

[edit] Error handling

Errors are reported as specified in math_errhandling .

If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur.

If base is zero and exp is zero, a domain error may occur.

If base is zero and exp is negative, a domain error or a pole error may occur.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • pow ( + 0 , exp ) , where exp is a negative odd integer, returns +∞ and raises FE_DIVBYZERO
  • pow ( — 0 , exp ) , where exp is a negative odd integer, returns -∞ and raises FE_DIVBYZERO
  • pow ( ± 0 , exp ) , where exp is negative, finite, and is an even integer or a non-integer, returns +∞ and raises FE_DIVBYZERO
  • pow ( ± 0 , — ∞ ) returns +∞ and may raise FE_DIVBYZERO
  • pow ( + 0 , exp ) , where exp is a positive odd integer, returns +0
  • pow ( — 0 , exp ) , where exp is a positive odd integer, returns -0
  • pow ( ± 0 , exp ) , where exp is positive non-integer or a positive even integer, returns +0
  • pow ( — 1 , ±∞ ) returns 1
  • pow ( + 1 , exp ) returns 1 for any exp , even when exp is NaN
  • pow ( base, ± 0 ) returns 1 for any base , even when base is NaN
  • pow ( base, exp ) returns NaN and raises FE_INVALID if base is finite and negative and exp is finite and non-integer.
  • pow ( base, — ∞ ) returns +∞ for any |base|
  • pow ( base, — ∞ ) returns +0 for any |base|>1
  • pow ( base, + ∞ ) returns +0 for any |base|
  • pow ( base, + ∞ ) returns +∞ for any |base|>1
  • pow ( — ∞, exp ) returns -0 if exp is a negative odd integer
  • pow ( — ∞, exp ) returns +0 if exp is a negative non-integer or negative even integer
  • pow ( — ∞, exp ) returns -∞ if exp is a positive odd integer
  • pow ( — ∞, exp ) returns +∞ if exp is a positive non-integer or positive even integer
  • pow ( + ∞, exp ) returns +0 for any negative exp
  • pow ( + ∞, exp ) returns +∞ for any positive exp
  • except where specified above, if any argument is NaN, NaN is returned

[edit] Notes

C++98 added overloads where exp has type int on top of C pow(), and the return type of std :: pow ( float , int ) was float . However, the additional overloads introduced in C++11 specify that std :: pow ( float , int ) should return double . LWG issue 550 was raised to target this conflict, and the resolution is to removed the extra int exp overloads.

Although std::pow cannot be used to obtain a root of a negative number, std::cbrt is provided for the common case where exp is 1/3.

The additional overloads are not required to be provided exactly as (A) . They only need to be sufficient to ensure that for their first argument num1 and second argument num2 :

  • If num1 or num2 has type long double , then std :: pow ( num1, num2 ) has the same effect as std :: pow ( static_cast < long double >( num1 ) ,
    static_cast < long double >( num2 ) ) .
  • Otherwise, if num1 and/or num2 has type double or an integer type, then std :: pow ( num1, num2 ) has the same effect as std :: pow ( static_cast < double >( num1 ) ,
    static_cast < double >( num2 ) ) .
  • Otherwise, if num1 or num2 has type float , then std :: pow ( num1, num2 ) has the same effect as std :: pow ( static_cast < float >( num1 ) ,
    static_cast < float >( num2 ) ) .

If num1 and num2 have arithmetic types, then std :: pow ( num1, num2 ) has the same effect as std :: pow ( static_cast < /* common-floating-point-type */ >( num1 ) ,
static_cast < /* common-floating-point-type */ >( num2 ) ) , where /* common-floating-point-type */ is the floating-point type with the greatest floating-point conversion rank and greatest floating-point conversion subrank between the types of num1 and num2 , arguments of integer type are considered to have the same floating-point conversion rank as double .

If no such floating-point type with the greatest rank and subrank exists, then overload resolution does not result in a usable candidate from the overloads provided.

[edit] Example

#include #include #include #include #include // #pragma STDC FENV_ACCESS ON int main() { // typical usage std::cout  "pow(2, 10) = "  std::pow(2, 10)  '\n'  "pow(2, 0.5) = "  std::pow(2, 0.5)  '\n'  "pow(-2, -3) = "  std::pow(-2, -3)  '\n'; // special values std::cout  "pow(-1, NAN) = "  std::pow(-1, NAN)  '\n'  "pow(+1, NAN) = "  std::pow(+1, NAN)  '\n'  "pow(INFINITY, 2) = "  std::pow(INFINITY, 2)  '\n'  "pow(INFINITY, -1) = "  std::pow(INFINITY, -1)  '\n'; // error handling errno = 0; std::feclearexcept(FE_ALL_EXCEPT); std::cout  "pow(-1, 1/3) = "  std::pow(-1, 1.0 / 3)  '\n'; if (errno == EDOM) std::cout  " errno == EDOM "  std::strerror(errno)  '\n'; if (std::fetestexcept(FE_INVALID)) std::cout  " FE_INVALID raised\n"; std::feclearexcept(FE_ALL_EXCEPT); std::cout  "pow(-0, -3) = "  std::pow(-0.0, -3)  '\n'; if (std::fetestexcept(FE_DIVBYZERO)) std::cout  " FE_DIVBYZERO raised\n"; }
pow(2, 10) = 1024 pow(2, 0.5) = 1.41421 pow(-2, -3) = -0.125 pow(-1, NAN) = nan pow(+1, NAN) = 1 pow(INFINITY, 2) = inf pow(INFINITY, -1) = 0 pow(-1, 1/3) = -nan errno == EDOM Numerical argument out of domain FE_INVALID raised pow(-0, -3) = -inf FE_DIVBYZERO raised

Источник

pow , powf , powl

Calculates x raised to the power of y .

Syntax

double pow( double x, double y ); float powf( float x, float y ); long double powl( long double x, long double y ); define pow(X, Y) // Requires C11 or higher double pow( double x, int y ); // C++ only float pow( float x, float y ); // C++ only float pow( float x, int y ); // C++ only long double pow( long double x, long double y ); // C++ only long double pow( long double x, int y ); // C++ only 

Parameters

Return value

Returns the value of x y . No error message is printed on overflow or underflow.

Values of x and y Return value of pow
x != 0.0 and y == 0.0 1
x == 0.0 and y == 0.0 1
x == 0.0 and y < 0 INF

Remarks

pow doesn’t recognize integral floating-point values greater than 2 64 (for example, 1.0E100).

pow has an implementation that uses Streaming SIMD Extensions 2 (SSE2). For information and restrictions about using the SSE2 implementation, see _set_SSE2_enable .

Because C++ allows overloading, you can call any of the various overloads of pow . In a C program, unless you’re using the macro to call this function, pow always takes two double values and returns a double value.

If you use the pow macro from , the type of the argument determines which version of the function is selected. See Type-generic math for details.

The pow(int, int) overload is no longer available. If you use this overload, the compiler may emit C2668. To avoid this problem, cast the first parameter to double , float , or long double .

Originally, the pow(T, int) overloads unrolled the pow call into a sequence of inline multiplication operations. While it was faster, it was also much less accurate. This implementation was removed in Visual Studio 2015 Update 1. For more information, see Conformance improvements in Visual Studio 2015 Update 1.

By default, this function’s global state is scoped to the application. To change this behavior, see Global state in the CRT.

Requirements

Routine Required header (C) Required header (C++)
pow , powf , powl or
pow macro

For more compatibility information, see Compatibility.

Example

// crt_pow.c #include #include int main( void )
2.0 to the power of 3.0 is 8.0 

Источник

Оцените статью