Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

c - Inexact float division

I were practicing some c programming when I saw this:

#include <stdio.h>

int main (void){
printf("result %.50lf",(double)10.0/10000000.0);
return 0;
}

And the result was 0.00000099999999999999995474811182588625868561393872

Can somebody explain me why happens this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The internal representation of double is a binary floating-point encoding that cannot precisely represent all (or indeed most) decimal fractions, for the same reason for example 1/3 cannot be exactly represented in decimal, 10.0/10000000.0 cannot be exactly represented in binary.

Moreover 64-bit double precision binary floating point has a precision of around 15 decimal significant figures so attempting to output 50 decimal places is always going to end up in irrelevant and meaningless digits. Your actual result within the precision of a double is 0.000000999999999999999.

See also: What Every Programmer Should Know About Floating-Point Arithmetic


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...