C
数值 | Numerics

sqrtf

sqrt, sqrtf, sqrtl

在头文件中定义
float sqrtf(float arg);(1)(自C99以来)
double sqrt(double arg);(2)
long double sqrtl(long double arg);(3)(自C99以来)
在头文件<tgmath.h>中定义
#define sqrt(arg)(4)(自C99以来)

1-3)计算平方根arg

4)类型 - 通用宏:如果arg有类型long doublesqrtl被调用。否则,如果arg有整数类型或类型doublesqrt则调用。否则,sqrtf被调用。如果arg是复杂的或虚,则宏调用相应的复变函数(csqrtfcsqrtcsqrtl)。

参数

arg-浮点值

返回值

如果没有错误发生arg,则返回(√arg)的平方根。

如果发生域错误,则返回实现定义的值(NaN,如果支持)。

如果由于下溢而发生范围错误,则返回正确的结果(舍入后)。

错误处理

按照math_errhandling中的指定报告错误。

如果arg小于零,则会发生域错误。

如果实现支持IEEE浮点运算(IEC 60559),

  • 如果参数小于-0,FE_INVALID则提高并返回NaN。

注意

sqrt是IEEE标准所要求的。唯一需要确定的其他操作是算术运算符和函数fma。在舍入到返回类型(使用默认舍入模式)后,结果sqrt与无限精确的结果无法区分。换句话说,误差小于0.5 ulp。其他功能,包括pow,并不那么受到限制。

示例

#include <stdio.h> #include <math.h> #include <errno.h> #include <fenv.h> #pragma STDC FENV_ACCESS ON int main(void) { // normal use printf("sqrt(100) = %f\n", sqrt(100) printf("sqrt(2) = %f\n", sqrt(2) printf("golden ratio = %f\n", (1+sqrt(5))/2 // special values printf("sqrt(-0) = %f\n", sqrt(-0.0) // error handling errno = 0; feclearexcept(FE_ALL_EXCEPT printf("sqrt(-1.0) = %f\n", sqrt(-1) if(errno == EDOM) perror(" errno == EDOM" if(fetestexcept(FE_INVALID)) puts(" FE_INVALID was raised" }

可能的输出:

sqrt(100) = 10.000000 sqrt(2) = 1.414214 golden ratio = 1.618034 sqrt(-0) = -0.000000 sqrt(-1.0) = -nan errno = EDOM: Numerical argument out of domain FE_INVALID was raised

参考

  • C11标准(ISO/IEC 9899:2011):

另请参阅

powpowfpowl(C99)(C99)计算一个给定的功率(xy)(函数)
cbrtcbrtfcbrtl(C99)(C99)(C99)计算立方根(3√x)(函数)
hypothypotfypotl(C99)(C99)(C99)计算两个给定数的平方和的平方根(√x2+ y2)(函数)
csqrtcsqrtfcsqrtl(C99)(C99)(C99)计算复平方根(函数)

| C ++文档sqrt |