为什么pow(int,int)这么慢? [英] Why is pow(int, int) so slow?

查看:285
本文介绍了为什么pow(int,int)这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在进行一些Euler练习项目,以提高对C ++的了解。

I've been working on a few project Euler exercises to improve my knowledge of C++.

我编写了以下函数:

int a = 0,b = 0,c = 0;

for (a = 1; a <= SUMTOTAL; a++)
{
    for (b = a+1; b <= SUMTOTAL-a; b++)
    {
        c = SUMTOTAL-(a+b);

        if (c == sqrt(pow(a,2)+pow(b,2)) && b < c)
        {
            std::cout << "a: " << a << " b: " << b << " c: "<< c << std::endl;
            std::cout << a * b * c << std::endl;
        }
    }
}

计算时间为17毫秒。

This computes in 17 milliseconds.

但是,如果我更改行

if (c == sqrt(pow(a,2)+pow(b,2)) && b < c)

if (c == sqrt((a*a)+(b*b)) && b < c)

计算时间为2毫秒。我是否缺少 pow(int,int)的一些明显的实现细节,这会使第一个表达式的计算变得如此缓慢?

the computation takes place in 2 milliseconds. Is there some obvious implementation detail of pow(int, int) that I'm missing which makes the first expression compute so much slower?

推荐答案

pow()使用实数浮点数,并在公式的内部使用

pow() works with real floating-point numbers and uses under the hood the formula

pow(x,y) = e^(y log(x))

计算 x ^ y int 在调用 pow 之前会转换为 double 。 ( log 是基于e的自然对数)

to calculate x^y. The int are converted to double before calling pow. (log is the natural logarithm, e-based)

x ^ 2 pow()的code>比 x * x 慢。

根据相关评论进行编辑


  • 使用 pow 甚至具有整数指数也可能会产生错误的结果( PaulMcKenzie

  • 除了将数学函数与 double一起使用之外, em>类型, pow 是函数调用(而 x * x 不是)( jtbandes

  • 实际上,许多现代编译器都会使用常量整数参数来优化pow,但这并不值得依赖。

  • Using pow even with integer exponents may yield incorrect results (PaulMcKenzie)
  • In addition to using a math function with double type, pow is a function call (while x*x isn't) (jtbandes)
  • Many modern compilers will in fact optimize out pow with constant integer arguments, but this should not be relied upon.

这篇关于为什么pow(int,int)这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆