I want to know the first double from 0d upwards that deviates by the long of the ‘same value’ by some delta, say 1e-8. I’m failing here though. I’m trying to do this in C although I usually use managed languages, just in case. Please help.
#include <stdio.h> #include <limits.h> #define DELTA 1e-8 int main() { double d = 0; // checked, the literal is fine long i; for (i = 0L; i < LONG_MAX; i++) { d=i; // gcc does the cast right, i checked if (d-i > DELTA || d-i < -DELTA) { printf('%f', d); break; } } }
I’m guessing that the issue is that d-i casts i to double and therefore d==i and then the difference is always 0. How else can I detect this properly — I’d prefer fun C casting over comparing strings, which would take forever.
ANSWER: is exactly as we expected. 2^53+1 = 9007199254740993 is the first point of difference according to standard C/UNIX/POSIX tools. Thanks much to pax for his program. And I guess mathematics wins again.
Doubles in IEE-754 have a precision of 52 bits which means they can store numbers accurately up to (at least)
251.If your longs are 32-bit, they will only have the (positive) range
0 .. 231 - 1so there is no 32-bit long that cannot be represented exactly as a double. For a 64-bit long, it will be (roughly)252so I’d be starting around there, not at zero.You can use the following program to detect where the failures start to occur. An earlier version I had relied on the fact that the last digit in a number that continuously doubles follows the sequence {2,4,8,6}. However, I opted eventually to use a known trusted tool
(bc)for checking the whole number, not just the last digit.Keep in mind that this may be affected by the actions of
sprintf()rather than the real accuracy of doubles (I don’t think so personally since it had no troubles with certain numbers up to2143).This is the test program I wrote:
This keeps going until:
which is roughly about where I’d expect it to fail.
As an aside, I originally used numbers of the form
2nbut that got me all the way up to:with the size of a double being 8 bytes (checked with
sizeof). It turned out these numbers were of the binary form1000...000, which can be represented for far longer with doubles. That’s when I switched to using2n + 1to get a better bit pattern (one at the start and one at the end).Now, just to be clear, the most reliable way would be to check every number to see which one fails first, but that’s going to have quite a long runtime. This approach is the best one given knowledge of the IEEE-754 encodings.