Math.Sqrt()的时间复杂度?

时间:2016-01-03 18:39:48

标签: c# big-o time-complexity math.sqrt

如何找到此功能的复杂性?

public void getListFromDb(){
    Cursor res = myDb.ViewAll();
    startManagingCursor(res);


    //Map cursor from db to viewFields
    String[] fromFieldNames = new String[]{DatabaseHelper.COL_2, DatabaseHelper.COL_3, DatabaseHelper.COL_4, DatabaseHelper.COL_5, DatabaseHelper.COL_6};
    int[] toViewIDS = new int[]{R.id.viewName, R.id.viewAddress, R.id.viewPostcode, R.id.viewType, R.id.imageView};

    //Create SimpleCursorAdaptor with null cursor
    SimpleCursorAdapter myCursorAdaptor = new SimpleCursorAdapter(this, R.layout.item_layout, null, fromFieldNames, toViewIDS, 0);
    // Set adaptor for listView
    myList.setAdapter(myCursorAdaptor);

    new AsyncTask<SimpleCursorAdapter, Void, Cursor>() {
        private SimpleCursorAdapter mSimpleCursorAdapter;
        @Override
        protected Cursor doInBackground(SimpleCursorAdapter... params) {
            // Save cursorAdapter to use in postExecute
            this.mSimpleCursorAdapter = params[0];
            // Load cursor on background thread with search function
               return myDb.ViewAll();
            }
        }

我知道以下部分是O(1):

private double EuclideanDistance(MFCC.MFCCFrame vec1, MFCC.MFCCFrame vec2)
{
  double Distance = 0.0;
  for (int K = 0; K < 13; K++)
     Distance += (vec1.Features[K] - vec2.Features[K]) * (vec1.Features[K] - vec2.Features[K]);
  return Math.Sqrt(Distance);
}

但我无法弄清楚double Distance = 0.0; for (int K = 0; K < 13; K++) Distance += (vec1.Features[K]-vec2.Features[K])*(vec1.Features[K]-vec2.Features[K]); 的复杂程度是什么。

2 个答案:

答案 0 :(得分:6)

您可以将其视为O(1):

  

换句话说,Math.Sqrt()转换为单个浮点   机器代码指令

源: c# Math.Sqrt Implementation

答案 1 :(得分:4)

BlackBear 所述,Math.Sqrt 实现将 a 转换为单个浮点机器代码指令 (fsqrt)。该指令的周期数是有界的(here 是一些示例)。这意味着它的复杂度是 O(1)。

这只是事实,因为我们使用了有限数量的浮点值。该操作的“实际”复杂度取决于输入的位数。 Here 您可以找到基本算术函数复杂度的列表。根据该列表,平方根函数具有乘法函数的复杂度(两个 n 位数字的复杂度为 O(n log n))。

您说,您假设加法和乘法函数的复杂度为 O(1)。这意味着,您可以假设平方根函数虽然慢得多,但也具有 O(1) 复杂度。