Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
879 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...