简体   繁体   English

为什么这个函数具有对数时间复杂度(计算数字的第n个根)?

[英]Why this function has logarithmic time complexity (calculating the nth root of a number)?

Last week, I was taking a specific MOOC about Computer Science, and the prof. 上周,我正在接受一个关于计算机科学和教授的特定MOOC。 used an inefficient way to calculate the square root of a number (he later showed other ways as well). 使用一种低效的方法来计算数字的平方根(他后来也展示了其他方法)。

Here's a function implemented in C++: 这是一个用C ++实现的函数:

double sqrt(double num)
{
    double eps = 0.001;
    double step = 0.001;

    double result = 0.0;

    while (num - (result * result) > eps)
    {
        result += step;
    }

    return result;
}

I know that the while loop will be executed (square root of num / step ) times. 我知道while循环将被执行( num / step平方根)次。

And I've decided to use matplotlib to draw a plot of this function growth for a range of numbers from 1 to 199 (inclusive), and here's the result: 我决定使用matplotlib绘制一个从1到199(含)的数字范围内的函数增长图,结果如下:

结果

Then, I compared it to (log(x) / step ) plot, and again here's the result: 然后,我将它与(log(x)/ step )图进行比较,并再次得到结果:

结果

And so, I have the following questions: 所以,我有以下问题:

  • Why it's logarithmic? 为什么它是对数的? and why this apply for any nth root of a number (using the above method) not only square root? 为什么这适用于数字的任何第n个根(使用上述方法)不仅仅是平方根?
  • What with that gap between sqrt growth and log(x)? sqrt增长和log(x)之间的差距是多少?

I'm aware that there's more efficient ways to achieve the same results of square root of a number, but I need someone to shed some light on this one. 我知道有更有效的方法可以达到数字平方根的相同结果,但我需要有人对这一点有所了解。

You are correct when you say that the loop is executed sqrt(num) times, and that makes its complexity √num. 当你说循环执行sqrt(num)次时你是正确的,这使得它的复杂性√num。 However, contrary to the later assumption, a square root isn't logarithmic: it's simply num^(1/2) , which makes it polynomial in the grand scheme of things. 然而,与后面的假设相反,平方根不是对数的:它只是num^(1/2) ,这使得它在宏观方案中是多项式的。

A clear sign and visual help is that it's not a straight line on a logarithmic plot: 一个明确的标志和视觉帮助是它在对数图上不是直线:

在此输入图像描述

The line on the left is a square root, and the line on the right is a base 10 logarithm. 左边的线是平方根,右边的线是10的对数。

The gap, obviously, is because it's not logarithmic. 显然,差距是因为它不是对数的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM