快速开方之魔法数 0x5f3759df

一、快速开方之魔法数 0x5f3759df

测试代码:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#define N_NUM 2147483640

float Q_rsqrt(float number)
{
	long i;
	float x2, y;
	const float threehalfs = 1.5F;

	x2 = number * 0.5F;
	y  = number;
	i  = * ( long * ) &y;						// evil floating point bit level hacking
	i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
	y  = * ( float * ) &i;
	y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//	y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

//#ifndef Q3_VM
//#ifdef __linux__
//	assert( !isnan(y) ); // bk010122 - FPE?
//#endif
//#endif
	return y;
}

int main()
{
	int i, j;
	float res;

	struct timeval start, end;
	int timeuse;

	printf("%f\n", 1.0/Q_rsqrt(3.14159));
	printf("%f\n", sqrt(3.14159));
	printf("%f\n", 1.0/Q_rsqrt(100));
	printf("%f\n", sqrt(100));

	gettimeofday(&start, NULL);
	for(i=0; i<N_NUM; i++){
		//for(j=0; j<N_NUM; j++) {
			res=1.0/Q_rsqrt(i);
			//res=0;
		//}
	}
	gettimeofday(&end, NULL);
	timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
	printf("time1=%.3fs\n", (double)timeuse/1000000);

	printf("done\n");
	gettimeofday(&start, NULL);
	for(i=0;i<N_NUM;i++){
		//for(j=0; j<N_NUM; j++) {
			res=sqrt(i);
			//res=0;
		//}
	}
	gettimeofday(&end, NULL);
	timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
	printf("time2=%.3fs\n", (double)timeuse/1000000);

    return 0;
}

运行结果:

1.773184

1.772453

10.015536

10.000000

time1=0.000s

done

time2=3.439s //耗时差距很大

相关推荐
20130924162716 小时前
1968年 Hart, Nilsson, Raphael 《最小成本路径启发式确定的形式基础》A* 算法深度研究报告
人工智能·算法
如何原谅奋力过但无声16 小时前
【力扣-Python-滑动窗口经典题】567.字符串的排列 | 424.替换后的最长重复字符 | 76.最小覆盖子串
算法·leetcode
玄冥剑尊17 小时前
贪心算法进阶
算法·贪心算法
玄冥剑尊17 小时前
贪心算法深化 I
算法·贪心算法
52Hz11817 小时前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
BHXDML17 小时前
第一章:线性回归& 逻辑回归
算法·逻辑回归·线性回归
iAkuya18 小时前
(leetcode)力扣100 二叉搜索树种第K小的元素(中序遍历||记录子树的节点数)
算法·leetcode·职场和发展
Remember_99319 小时前
【LeetCode精选算法】滑动窗口专题二
java·开发语言·数据结构·算法·leetcode
Gorgous—l20 小时前
数据结构算法学习:LeetCode热题100-动态规划篇(下)(单词拆分、最长递增子序列、乘积最大子数组、分割等和子集、最长有效括号)
数据结构·学习·算法
北京地铁1号线20 小时前
2.3 相似度算法详解:Cosine Similarity 与 Euclidean Distance
算法·余弦相似度