[英]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.