C++ precision of numbers and truncation with fstream

霸气de小男生 提交于 2020-01-11 09:51:28

问题


I have a file.txt with hundreds of numbers. They have many digits (max 20) after the point and I need to get them all without truncation, otherwise they introduce errors in the following computations. I made these numbers with matlab so it has a monstrous precision but now I must replicate this behaviour in my program.

I've done this way:

 fstream in;
 in.open(file.txt, ios::in);
 long double number;
 in>>number;

I also tried this

 in.precision(20);
 in>>number;

before each ">>" operation but it is vain


回答1:


The following works fine on my system (Win7, VS2012):

#include <fstream>
#include <iostream>

int main (void)
{
    std::ifstream file ("test.txt") ;

    long double d = 0 ;
    file >> d ;

    std::cout.precision (20) ;
    std::cout << d << "\n" ;


    return 0 ;
}

The text file:

2.7239385667867091

The output:

2.7239385667867091

If this doesn't work on your system, then you need to use a third-party number library.




回答2:


std::numeric_limits::min std::numeric_limits::digits10 can tell you what your target's actual precision is for long double.

If you find that it's insufficient to represent your data, you probably want arbitrary precision. There are a couple of arbitrary precision number libraries you can use, none of which are standard in C++.

  • boost::multiprecision
  • GNU MP
  • MPFR


来源:https://stackoverflow.com/questions/24415756/c-precision-of-numbers-and-truncation-with-fstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!