做视频算法10多年,经常要算绝对值,整数的绝对值有快速算法,但浮点数的绝对值没看到有快速算法,经常不段发现,得到如下浮点数的快速算法:
快6倍多,
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
union funion{
float fnum;
BYTE bnum[4];
} ;
float fabs_11(float x)
{
return (x < 0) ? -x : x;
}
void main(void)
{
int iTime;
float ret;
union funion tmp1,tmp2;
float x =- 2110000.0001;
iTime = GetTickCount();
for(; x < 2210000.987;x+=0.3)
{
tmp1.fnum = x;
//printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp1.fnum,tmp1.bnum[3],tmp1.bnum[2],tmp1.bnum[1],tmp1.bnum[0]);
// printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp2.fnum,tmp2.bnum[3],tmp2.bnum[2],tmp2.bnum[1],tmp2.bnum[0]);
tmp1.bnum[3] = tmp1.bnum[3]&0x7f;
//printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp1.fnum,tmp1.bnum[3],tmp1.bnum[2],tmp1.bnum[1],tmp1.bnum[0]);
// printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp2.fnum,tmp2.bnum[3],tmp2.bnum[2],tmp2.bnum[1],tmp2.bnum[0]);
}
printf("gai time = %d\n",GetTickCount() - iTime);
iTime = GetTickCount();
x =- 2110000.0001;
for(; x < 2210000.987;x+=0.3)
{
fabs_11(x);
}
printf("old time = %d\n",GetTickCount() - iTime);
}
如果浮点数是double,将如何生成呢?
请大家先想想,后看答案。
//
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
union funion{
double fnum;
BYTE bnum[8];
} ;
double fabs_11(double x)
{
return (x < 0) ? -x : x;
}
void main(void)
{
int iTime;
double ret;
union funion tmp1,tmp2;
double x =- 2110000.0001;
iTime = GetTickCount();
for(; x < 2210000.987;x+=0.3)
{
tmp1.fnum = x;
printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp1.fnum,tmp1.bnum[3],tmp1.bnum[2],tmp1.bnum[1],tmp1.bnum[0]);
// printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp2.fnum,tmp2.bnum[3],tmp2.bnum[2],tmp2.bnum[1],tmp2.bnum[0]);
tmp1.bnum[7] = tmp1.bnum[7]&0x7f;
printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp1.fnum,tmp1.bnum[3],tmp1.bnum[2],tmp1.bnum[1],tmp1.bnum[0]);
// printf("%f\t%2.2x%2.2x%2.2x%2.2x\n",tmp2.fnum,tmp2.bnum[3],tmp2.bnum[2],tmp2.bnum[1],tmp2.bnum[0]);
}
printf("gai time = %d\n",GetTickCount() - iTime);
iTime = GetTickCount();
x =- 2110000.0001;
for(; x < 2210000.987;x+=0.3)
{
fabs_11(x);
}
printf("old time = %d\n",GetTickCount() - iTime);
}