2012-08-14 46 views
-6

在這裏,我從一個浮點變量中減去128.0和129.0倍。當操作數小於129時,C++ float不會改變。

#include "stdafx.h" 
#include<stdlib.h> //is this the problem? Or am i doing something wrong? 
int main() 
{ 

float d1=3.0e9; 
printf("\n before: %f \n",d1); 
for(int i=0;i<2000000;i++) d1=d1-128.0; //doesnt change!  
printf("\n after : %f \n",d1); 
for(int i=0;i<2000000;i++) d1=d1-129.0; //does change! 
printf("\n after2: %f \n",d1); 

//is 129 is the minimum step for sub/add ? Isnt this wrong? 
//Is this about exponential part 10^9 ? 
getchar(); 
return 0; 
} 

輸出:

enter image description here

問:爲什麼這個浮動不加改變/由操作數底塗小則129?因爲我選擇初始浮點值3.0e9?

當我選擇初始值3.0e10,初始化和兩個減法都不工作。

當我選擇初始值3.0e8,最小變化是17.所以16不會改變。 :(

所以,感謝的答案,當初始值變小,最小步根據精密變小。

VC++ 2010快件中,Windows XP 32位。奔騰-M

+8

A *文本截圖* - 嚴重嗎? – 2012-08-14 12:23:55

+1

我按打印屏幕並複製文件比寫3 floats – 2012-08-14 12:26:28

+1

@tuğrulbüyükışık更快,你應該打開quickedit模式,並使用鼠標複製文本。或者只需右鍵單擊並使用菜單進入「選擇」模式。 – Ben 2012-08-14 12:31:44

回答

5

我們可以理解這是怎麼回事通過觀察32-bit float的解剖結構。 IEEE754格式的值3.0E90x4F32D05E,指數值爲31(可以使用this online calculator查找該值)。

現在我們有23個子統一的二進制數字留給尾數。這意味着最小增量,即,尾數的相鄰值之間的差,爲31   − =   8.自128與二進制的數是2 ,我們看到,它是足夠小隻是尾數的尾數會減少,而129大到足以可見。

+1

這真的很有幫助 – 2012-08-14 12:34:50

5

這是因爲你的初始值。一個浮點只能容納數字量小,所以它不能代表操作的結果,它是四捨五入到最接近的值。

+0

(有效數字) – 2012-08-14 12:29:17

+0

感謝您的支持 – 2012-08-14 12:33:26

相關問題