简体   繁体   中英

How is printf printing 53 digits after decimal point?

I was trying to print the square root of a number at some given precision.

int N;
int precision;
cin>>N>>precision;
printf("%.*lf",precision,std::sqrt(N));

and this is what clang++ printed out:

%./a.out
2 100
1.4142135623730951454746218587388284504413604736328125000000000000000000000000000000000000000000000000

It was able to print over 50 digits of precision? I thought doubles could only handle 17 digits?

I'm running clang++ on apple silicon m1

Among the set of 64-bit floating-point values, sqrt(2) is closest to the floating-point value that exactly corresponds to the fraction 6369051672525773/4503599627370496 . It's this rational number, or 1.4142135623730951454746218587388284504413604736328125 in decimal, that printf() is printing with as much precision as you tell it to.

The 17-digit limit refers to the number of significant decimal digits required to distinguish any two floating-point numbers. In other words, if you print a floating-point number with 17 significant digits of precision, and read it back, you are guaranteed to get the same floating-point number (to the last bit) as the one you started with.

The conversion in the other direction, where you start with a decimal number, convert it into floating-point (ie approximate it to the closest fraction with a 53-bit numerator and a power-of-two denominator), and then display it as decimal, only guarantees to preserve 15 decimal digits. For example, the decimal number 0.1234567890123456789 will be approximated to 8895999183877727/72057594037927936 , which is 0.12345678901234567736988623209981597028672695159912109375 . In this case the first 17 digits (counting from 1 ) of the printed floating-point value correspond to the original number.

It was able to print over 50 digits of precision? I thought doubles could only handle 17 digits?

It's false precision because you asked for it.

Say I ask someone how tall a building is and they say "oh, about 50 meters". If you ask me to give that to you in feet to five decimal places, I can -- 164.04199 feet. But the precision is false.

Check it out:
Output: 1.414213562373095145474621858738828450441...
Correct: 1.414213562373095048801688724209698078569...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM