程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> C語言之linux內核實現平方根計算算法

C語言之linux內核實現平方根計算算法

編輯:關於C

關於平方根的計算,在linux內核中也有實現,就像math.h數學庫裡的sqrt這個函數一樣。

平方根的公式定義:

如果一個非負數x的平方等於a,即 \\ ,那麼這個非負數x叫做a的算術平方根。a的算術平方根記為 \ ,讀作“根號a”,a叫做被開方數(radicand)。求一個非負數a的平方根的運算叫做開平方。結論:被開方數越大,對應的算術平方根也越大(對所有正數都成立)。 一個正數如果有平方根,那麼必定有兩個,它們互為相反數。顯然,如果我們知道了這兩個平方根的一個,那麼就可以及時的根據相反數的概念得到它的另一個平方根。 哈哈,小學生都懂,不解釋不解釋,直接來看代碼:大笑 一樣的,從內核裡把代碼取出來:
#include 
#ifdef CONFIG_64BIT
#define BITS_PER_LONG 64
#else
#define BITS_PER_LONG 32
#endif
/**
 * int_sqrt - rough approximation to sqrt
 * @x: integer of which to calculate the sqrt
 *
 * A very rough approximation to the sqrt() function.
 */
unsigned long int_sqrt(unsigned long x)
{
	unsigned long op, res, one;
	op = x;
	res = 0;
	one = 1UL << (BITS_PER_LONG - 2);
	while (one > op)
		one >>= 2;

	while (one != 0) {
		if (op >= res + one) {
			op = op - (res + one);
			res = res +  2 * one;
		}
		res /= 2;
		one /= 4;
	}
	return res;
}

int main(void)
{
	printf("%d\n",int_sqrt(16))	;
	return 0 ;
}
運行結果: \
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved