zzh1996
zzh1996

Reputation: 500

How does computer convert floating point numbers to decimal string?

When I run the following code, the output is accurately the number 2500 in decimal.

(g++ 5.3.1 on ubuntu)

#include<iostream>
#include<cmath>

using namespace std;

int main(){
    cout.precision(0);
    cout << fixed << pow(2.0,500.0);
    return 0;
}

I wonder how C++ converted this floating point number to its decimal string at such a high precision.

I know that 2500 can be accurately presented in IEEE 754 format. But I think mod 10 and divided by 10 can cause precision loss on floating point numbers. What algorithm is used when the conversion proceed?

Upvotes: 1

Views: 1163

Answers (1)

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

Yes, there exists an exact double-precision floating-point representation for 2500. You should not assume that pow(2.0,500.0) produces this value, though. There is no guarantee of accuracy for the function pow, and you may find SO questions that arose from pow(10.0, 2.0) not producing 100.0, although the mathematical result was perfectly representable too.

But anyway, to answer your question, the conversion from the floating-point binary representation to decimal does not in general rely on floating-point operations, which indeed would be too inaccurate for the intended accuracy of the end result. In general, accurate conversion requires reliance on big integer arithmetics. In the case of 2500, for instance, the naïve algorithm would be to repeatedly divide the big integer written in binary 1000…<500 zeroes in total>… by ten.

There are some cases where floating-point arithmetic can be used, for instance taking advantage of the fact that powers of 10 up to 1023 are represented exactly in IEEE 754 double-precision. But correctly rounded conversion between binary floating-point and decimal floating-point always require big integer arithmetics in general, and this is particularly visible far away from 1.0.

Upvotes: 3

Related Questions