[英]Unary operator in C or C++ for the second power of a number
Given a double x
, it is known that it is more efficient to use x*x
instead of pow(x,2)
. 给定一个
double x
,已知使用x*x
代替pow(x,2)
效率更高。 Imagine for simplicity that we have to calculate the square root of x
: as it is a unary operation, for this purpose we have sqrt(x)
. 为简单起见,想象一下我们必须计算
x
平方根:由于它是一元运算,因此有sqrt(x)
。 Now, also raising x
to the second power is a unary operation, but we have nothing like (as far as I know) pow2(x)
. 现在,将
x
升至第二幂也是一元运算,但据我所知,我们没有pow2(x)
。
I implemented my own pow2
as: 我将自己的
pow2
实现为:
inline double pow2(double a){return a*a;}
which should be still better than pow(a,2)
, but it is based on the *
operator that is not unary. 应该比
pow(a,2)
更好,但是它基于*
运算符,该运算符不是一元的。 How to implement a genuine unary implementation of pow2
? 如何实现
pow2
的真正一元实现? Would it be the most efficient way to obtain the second power of a double
? 这是获得
double
二次幂的最有效方法吗?
NOTE: I am aware of the fact that every real power of a positive real is an unary operation and that it is nonsense to define an infinite number of pow2
, pow3
, pow3.14
... from the practical point of view I'm very happy with pow(double, double)
. 注意:我知道一个事实,即一个正实数的每一个实数都是一元运算,从实际的角度来看,定义无限个
pow2
, pow3
, pow3.14
...是无稽之谈对pow(double, double)
非常满意。
"it is more efficient to use
x*x
instead ofpow(x,2)
"“使用
x*x
代替pow(x,2)
更有效”
Not certainly more efficient. 不一定更有效率。 It might be the same.
可能是一样的。 C allows analyze-ability of such functions like
pow()
and both may emit the same code. C允许像
pow()
这样的函数进行分析,并且两者都可以发出相同的代码。
A compiler may not analyze your pow2()
and create sub-optimal code as compared to pow(a,2)
. 与
pow(a,2)
相比,编译器可能不会分析pow2()
并创建次优代码。
If truly concerned, profile your code. 如果确实需要,请分析您的代码。 Yet what is best on one platform may differ on others.
但是,在一个平台上最好的选择可能在其他平台上有所不同。
How to implement a genuine unary implementation of pow2?
如何实现pow2的真正一元实现?
inline double pow2(double a){return a*a;}
is OK. inline double pow2(double a){return a*a;}
可以。
Would it be the most efficient way to obtain the second power of a double?
这是获得双倍底数次幂的最有效方法吗?
"most efficient" --> I suggest no function, just x*x
. “最有效的”->我建议没有功能,只有
x*x
。
Also note that C allows FP to evaluate at higher precision that required. 另请注意,C允许FP以所需的更高精确度进行评估。 Research
FLT_EVL_METHOD
. 研究
FLT_EVL_METHOD
。 The goal for most efficient way to obtain the second power of a double with a function may defeat overall performance. 最有效的方法来获得具有功能的双精度数的二次方的目标可能会破坏总体性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.