vish213
vish213

Reputation: 786

Why do float calculation results differ in C and on my calculator?

I am working on a problem and my results returned by C program are not as good as returned by a simple calculator, not equally precise to be precise. On my calculator, when I divide 2000008 by 3, I get 666669.333333 But in my C program, I am getting 666669.312500 This is what I'm doing-

printf("%f\n",2000008/(float)3);

Why are results different? What should i do to get the result same as that of calculator? I tried double but then it returns result in a different format. Do I need to go through conversion and all? Please help.

Upvotes: 1

Views: 462

Answers (2)

kviiri
kviiri

Reputation: 3302

Floating point numbers take a fixed amount of memory and therefore have a limited precision. Limited precision means you can't represent all possible real numbers, and that in turn means that some calculations result in rounding errors. Use double instead of float to gain extra precision, but mind you that even a double can't represent everything even if it's enough for most practical purposes.

Gunthram summarizes it very well in his answer:

What it boils down to is, you should never assume floating point numbers to be precise. They aren't.

Upvotes: 1

Guntram Blohm
Guntram Blohm

Reputation: 9819

See http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html for an in-depth explanation.

In short, floating point numbers are approximations to the real numbers, and they have a limit on digits they can hold. With float, this limit is quite small, with doubles, it's more, but still not perfect.

Try

printf("%20.12lf\n",(double)2000008/(double)3);

and you'll see a better, but still not perfect result. What it boils down to is, you should never assume floating point numbers to be precise. They aren't.

Upvotes: 3

Related Questions