存储浮点数时的c ++精度问题 [英] c++ precision issue in storing floating point numbers

查看:51
本文介绍了存储浮点数时的c ++精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些数学计算.我正在失去精度.但是我需要极高的精度.然后,我用下面给出的代码检查精度问题.有什么解决办法可以提高精度?

  #include< iostream>#include< stdlib.h>#include< cstdio>#include< sstream>#include< iomanip>使用命名空间std;int main(int argc,char ** arvx){浮点数f = 1.00000001;cout<<"f:"<< std :: setprecision(20)<<f<< endl;返回0;} 

输出为f:1

解决方案

如果您确实想要这些数字的精确表示形式(即,分数成分非常小,则小数点后还有很多地方),则浮点类型(例如 float 或什至更精确的 double )可能仍无法在所有情况下为您提供所需的确切结果.浮点类型只能近似使用小数部分的某些值.

您可能需要使用某种高精度的定点C ++类型,以便对值中的很小一部分进行精确表示,并在对此类值执行数学运算时得到准确的计算结果.数字.以下问题/解答可能为您提供一些有用的指导: C ++定点库?

I'm handling some mathematical calculation. I'm losing precision. But i need extreme precision. I then used to check the precision issue with the code given below. Any solution for getting the precision?

#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include <sstream>
#include <iomanip>
using namespace std;



int main(int argc,char** arvx)
{
   float f = 1.00000001;
   cout << "f: " <<std::setprecision(20)<< f <<endl;
   return 0;
}

Output is f: 1

解决方案

If you truly want precise representation of these sorts of numbers (ie, with very small fractional components many places beyond the decimal point), then floating point types like float or even the much more precise double may still not give you the exact results you are looking for in all circumstances. Floating point types can only approximate some values with small fractional components.

You may need to use some sort of high precision fixed point C++ type in order to get exact representation of very small fractions in your values, and resulting accurate calculated results when you perform mathematical operations on such numbers. The following question/answers may provide you with some useful pointers: C++ fixed point library?

这篇关于存储浮点数时的c ++精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆