Ramsin Khoshaba
Ramsin Khoshaba

Reputation: 33

double and accuracy

Using long double I get 18/19 = 0.947368421052631578..., and 947368421052631578 is the repeating decimal. Using double I get 0.947368421052631526... However, the former is correct. Why such an incorrect result?

Upvotes: 1

Views: 12510

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753990

A double typically provides 16(±1) decimal digits. Your example shows this:

     4   8  12  16
     v   v   v   v
0.947368421052631578 long double
0.947368421052631526 double

The answers agree to 16 digits. This is what should be expected. Also, note that there's no guarantee in the C Standard that a long double has more precision than a double.

The last decimal digit (16th or 17th) is not necessarily accurate after math operations (at least not in all implementations and platforms); hence, limit your code to 15 digits.

Upvotes: 12

Mark Ransom
Mark Ransom

Reputation: 308206

A double which is usually implemented with IEEE 754 will be accurate to between 15 and 17 decimal digits. Anything past that can't be trusted, even if you can make the compiler display it.

Upvotes: 6

Paul Rubel
Paul Rubel

Reputation: 27222

You're trying to represent every decimal number with a finite amount of bits. Some things just aren't expressible exactly in floating point. Expecting exact answers with floats is your first problem. Take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic

Here's a summary from some lecture notes:

As mentioned earlier, computers cannot represent real numbers precisely since there are only a finite number of bits for storing a real number. Therefore, any number that has infinite number of digits such as 1/3, the square root of 2 and PI cannot be represented completely. Moreover, even a number of finite number of digits cannot be represented precisely because of the way of encoding real numbers.

Upvotes: 9

Related Questions