我目前正在嘗試深入瞭解浮點數表示法,所以我玩了一下。在這樣做的時候,我偶然發現了一些奇怪的行爲;我無法弄清楚發生了什麼事情,我會非常感謝一些見解。如果這已被回答道歉,我發現它很難谷歌!比較cast float爲零時的奇怪行爲
#include <iostream>
#include <cmath>
using namespace std;
int main(){
float minVal = pow(2,-149); // set to smallest float possible
float nextCheck = static_cast<float>(minVal/2.0f); // divide by two
bool isZero = (static_cast<float>(minVal/2.0f) == 0.0f); // this evaluates to false
bool isZero2 = (nextCheck == 0.0f); // this evaluates to true
cout << nextCheck << " " << isZero << " " << isZero2 << endl;
// this outputs 0 0 1
return 0;
}
本質上發生的事情是:
- 我設置MINVAL是可以使用 單精度
- 除以2應產生0表示的最小浮動 - 我們在最小
- 確實,isZero2確實返回true,但isZero返回false。
發生了什麼 - 我會認爲它們是相同的?編譯器是否很聰明,說劃分任何數字都不可能產生零?
感謝您的幫助!
你怎麼確定'pow(2,-149)'返回最小可能的浮點數?有很多計算不準確的問題。 – deepmax 2014-11-01 14:32:47
它似乎工作。二進制表示返回1,這確實是最小可能的浮點數: Sign = 0; Exponent = 0; Mantissa = 1,因此: 2 ^( - 23)* 2 ^( - 126)= 2 ^( - 149) – noctilux 2014-11-01 14:39:28
我在g ++ 4.8.2上得到您的預期輸出。 '0 1 1'。 – 2014-11-01 14:40:43