在c中使用pow()函数的算法是什么? [英] what algorithm is used to pow() function in c
问题描述
#include< stdio.h>
#include< math.h>
int main(){
double n,p,ans;
while(scanf(%lf%lf,& n,& p)== 2)
{
ans = pow(p,(1 / n));
printf(%。0lf\\\
,ans);
}
return 0;
$ / code>
在这里使用什么算法来查找。这个pow()函数的复杂性是什么?
C99标准的第4.12.7.4节没有更多
$ b
strong>
#include< math.h>
double pow(double x,double y);
float powf(float x,float y);
long double powl(long double x,long double y);
描述
< pow
函数计算 x
上升到 y
。如果 x
有限且负数,并且 y
有限且不是整数值,则会发生域错误。范围错误可能会发生。如果 x
为零且 y
为零,则可能会出现域错误。如果 x
为零且 y
小于零,则可能会出现域错误或范围错误。
$ b
退货 请注意,没有给出有关函数复杂性的信息,也没有关于要使用的算法的预期。这是因为在C的某些实现中,函数可能是处理器本身的,而在其他体系结构中,浮点处理不是由硬件提供的。 假设复杂度不低于 在许多FP单元平台上,base -e指数,浮点乘法和自然对数都需要 -edit2-我不太清楚
$ b x
上升到 y
]。
log
,乘法和 exp
的组合:
double pow(double x,double y){
return exp(log(x)* y);
$ b O(1)
时间,所以 pow
也应该是这样。
exp
和 log $ c $的复杂性c>,但我认为实现使用泰勒近似和一堆查找表。这仍然会给
O(1)
。
#include<stdio.h> #include<math.h> int main() { double n,p,ans; while(scanf("%lf %lf",&n,&p)==2) { ans=pow(p,(1/n)); printf("%.0lf\n",ans); } return 0; }
what algorithm is used to find ans here.what is the complexity of this pow() function?.
Section 4.12.7.4 of the C99 standard has nothing more to say about the pow
functions than the following:
Synopsys
#include <math.h> double pow(double x, double y); float powf(float x, float y); long double powl(long double x, long double y);
Description
The
pow
functions computex
raised to the powery
. A domain error occurs ifx
is finite and negative andy
is finite and not an integer value. A range error may occur. A domain error may occur ifx
is zero andy
is zero. A domain error or range error may occur ifx
is zero andy
is less than zero.Returns
The
pow
functions return [x
raised to the powery
].
Note that no information is given about the complexity of the function, and that there are no expectations about the algorithm to be used. This is because the functions could be native to the processor in some implementations of C, while on other architectures, floating-point processing isn't provided by hardware.
You can assume, though, that the complexity is not worse than that of log
, multiplication and exp
combined:
double pow(double x, double y) {
return exp(log(x)*y);
}
On many platforms with an FP unit, base-e exponentiation, floating-point multiplication, and natural logarithms all take O(1)
time, so pow
should too.
-edit2- I'm not so sure anymore about the complexities for exp
and log
, but I think implementations use Taylor approximation and a bunch of lookup tables. That would still give O(1)
.
这篇关于在c中使用pow()函数的算法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!