If I want to create a space of integers from say $n_1$ to some $n_2$ with step $dn>0$, what is the number of elements of that set? I am thinking $N=\frac{n2-n1}{dn} + 1$ but this will produce a non-integer number, but i guess the number of elements will be simply the integer part of $N$. Is that correct?
A bigger problem is when the numbers $n_1$ and $n_2$ and $dn$ are no longer integers but real values. The above does not work. E.g. I take in matlab (this is just to illustrate since i have not found simpler numbers to show it):
n1=126187265.1839116960763931;
n2=157723265.1839116811752319;
dn=300;
a = n1:dn:n2;
then the size of a will be 105121 but the formula produces 105120. What would the formula be like for real numbers?
he problem likely comes down to limited precision. If we do the calculations exactly (using fractions, for example), we find that $1 + \lfloor{\frac{n2 - n1}{dn}}\rfloor$ is in fact 105120 and there are in fact exactly 105120 numbers between
n1andn2with a step of $300$.I believe Matlab uses 64-bit floating point by default, which means that your
n1is represented in memory as0x419E15DC04BC5359. The first bit is the sign, which is 0 here (meaning positive). The next 11 bits are the exponent of 2, offset by 1023, which is 1049 - 1023 = 26 here. These two parts make up the first three hexadecimal digits (0x419here). The rest is the fractional part, or0xE15DC04BC5359= $3964684390388569$. We can reconstruct (what the computer thinks)n1as $(1 + 3964684390388569 \times 2^{-52}) \times 2^{26}$.Then,
n1 + 300*105120is represented0x41A2CD55025E29AC, which is exactly the same representation asn2 = 0x41A2CD55025E29AC. So Matlab goes ahead and includes it in the range, even though it wouldn't be if we had sufficient precision.n1 + 300*105120is actually $157723265.1839116960763931$, which is larger thann2.So what happened? For numbers around
n2, we have a precision of $2^{-25}$. That is, the next number we can represent after a given number (around the size ofn2) is $2^{-25}$ larger. The fractional parts ofn1(and hencen1 + 105120*300) andn2are slightly more than $2^{-26}$ apart. So to the nearest precision we can get, they're equal.The same rounding error doesn't happen with your formula due to essentially the same thing. For numbers around
n1, we have precision of $2^{-26}$, so we should be able to distinguish the fractional parts ofn1andn2because they're more than $2^{-26}$ apart.