[英]Discrepancy between frexp and ldexp
考慮以下:
#include <iostream>
//#include <math.h>
#include <cmath>
using namespace std;
int main(int argc, char **argv)
{
double ldexp_signif = 0.545528;
double ldexp_expo = 12;
double ldexp_output = 0;
double frexp_input = 2234.484565523;
double frexp_signif = 0;
int frexp_expo = 0;
int n;
// create float from sig and expo
ldexp_output = ldexp (ldexp_signif , ldexp_expo);
printf ("The significand INPUT is %f\n",ldexp_signif);
printf ("The exponent INPUT is %f\n",ldexp_expo);
printf ("The float OUTPUT is %f\n\n",ldexp_output);
// get sig and expo from float
frexp_signif = frexp (frexp_input , &frexp_expo);
printf ("The float INPUT is %f\n",frexp_input);
printf ("the exponent OUTPUT is %i\n",frexp_expo);
printf ("The significand OUTPUT is %f\n",frexp_signif);
// ==================================
cout << endl << "=======================================" << endl << "Program completed and terminated successfully." << endl << "Press enter to exit";
cin.ignore();
return 0;
}
輸出為:
The significand INPUT is 0.545528
The exponent INPUT is 12.000000
The float OUTPUT is 2234.482688
The float INPUT is 2234.484566
the exponent OUTPUT is 12
The significand OUTPUT is 0.545528
=======================================
Program completed and terminated successfully.
Press enter to exit
我想知道的是,當ldexp被賦予相同的有效值和frexp生成的指數時,為什么ldexp給出的浮點輸出不同於frexp的浮點輸入? 我找到了這篇文章,但是那篇文章沒有回答我的問題。 我也看到了這一點 ,它指出浮點計算不准確。 控制台的輸出僅用於演示目的,要從使用單精度浮點格式寫入的游戲數據文件中讀取有效位數和指數,然后將其用於顯示該數據,而不用將其用於任何用途可能會危及生命,例如在醫療或軍事應用中,我應該按原樣使用它還是尋找更准確的解決方案?
以下假設IEEE 754使用其基本的64位二進制浮點格式。
源文本double frexp_input = 2234.484565523;
將frexp_input
初始化為2234.484565523000128450803458690643310546875。
然后frexp
將指數設置為12並返回0.545528458379638703235059438156895339488983154296875。
用%f
打印該值將顯示“ 0.545528”,這是一個不同數字的十進制數字,因為實際值0.545528458379638703235059059156895339488983154296875已四舍五入顯示。
當源文本中使用該數字.545528時, double ldexp_signif = 0.545528;
,它將ldexp_signif
初始化為0.54552800000000001290345608140341937541961669921875。
當使用ldexp
將其乘以2 12時 ,結果為2234.48268800000005285255610942840576171875。
再次使用%f
打印該值將顯示“ 2234.482688”,因為該數字已四舍五入以顯示。
簡介: ldexp
沒有給出frexp
生成的有效frexp
。 frexp
生成的有效frexp
為0.545528458379638703235059438156895339488983154296875,而ldexp的有效ldexp
為0.54552800000000001290345608140341937541961669921875。 這些是不同的,因此獲得了不同的結果。
觀察到有效數在其第七個有效數字附近變化,並且縮放的值在其第七個有效數字附近變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.