1. 程式人生 > >[C&C++]半精度浮點誤差實驗

[C&C++]半精度浮點誤差實驗

// half_float_verify.cpp : 定義控制檯應用程式的入口點。
// by Zhonglihao 2018

#include "stdafx.h"
#include "stdlib.h"
#include "stdio.h"

//強制裁掉指數位的低16位
unsigned short FloatToShort(float x)
{
	unsigned short y;
	y = (unsigned short)((*(unsigned int *)(&x)) >> 16);
	return y;
}

//恢復為32位
float ShortToFloat(unsigned short x)
{
	float y;
	unsigned int temp;
	temp = ((unsigned int)(x << 16));

	y = (float)(*((float *)(&temp)));
	return y;
}


int _tmain(int argc, _TCHAR* argv[])
{
	unsigned short i;
	float arr[65536] = { 0 }; //存放 0 - 65536的浮點數
	float full_float_num;
	float half_float_num;

	//迴圈產生 0 - 65536 數值
	for (i = 0; i <= 0xffff; i++)
	{
		//列印迴圈的值
		printf("%f\n", (float)i);

		//除以一個整數以變為小數
		full_float_num = (float)i / 1000.0;

		//將浮點值的低16位剪裁,並從16位儲存轉為浮點
		half_float_num = ShortToFloat(FloatToShort(full_float_num));

		//觀察誤差情況
		arr[i] = half_float_num - full_float_num;

		if (i == 0xffff) break;
	}


	//寫入誤差結果到excel檔案
	FILE *fp = NULL;
	errno_t err;
	err = fopen_s(&fp, "C:\\Users\\Administrator.5UPANNKI9OCMVXP\\Desktop\\test0825\\test.xls", "w");
	for (i = 0; i <= 0xffff; i++)
	{
		fprintf(fp, "%f\n", arr[i]);
		if (i == 0xffff) break;
	}
	fclose(fp);

	//system("Pause");

	return 0;
}

輸出的excel,觀察機械截斷低16位的float誤差: