3 ms·
Is there an example of where 1 is better for math, or is it just a familiarity thing?
by skohan 6y ago
Is there an example of where 1 is better for math, or is it just a familiarity thing?
- SatvikBeri 6y agoAs a trivial example, if you want to get the sum of the first n numbers, that's `sum(range(n+1))` in Python. Or if you want to get all the prime numbers <= n, find the triangular numbers, etc. In general you end up with a lot of `n+1`s and it's easy to lose track or miss some, and end up with a silent, non-crashing error that produces the wrong result because you're accidentally leaving out the last element of your input.
- socialdemocrat 6y agoMost math books are written in a way where 1 is the first element. So if you take math examples and translate to code, it works more naturally. Also this is how you talk normally. You don't talk about the zeroth-column or zeroth-row in daily speech. You talk about first column and first row. Only reason 0 based indexing make sense to me is because I began programming as a teenagers and was forced to get accustomed to it. But I remember struggling with it. Yes when working with memory, pointers etc it is more elegant. But if you are not, then I think 1-based indexing looks better.
- FridgeSeal 6y agoZero based indexing came from early requirements to address things in arrays using offsets. Subsequent languages don’t have this issue, and when you think about it, it causes a weird disconnect: 1-based indexing corresponds exactly with how you think about and see elements in a collection. 0 based indexing-despite how comfortable one gets with it requires additional arithmetic. It’s a relic from the past, and unless you’re doing the very specific thing of indexing via offset instead of position, there’s no reason to hang onto this anachronism.
- cbkeller 6y agoLinear algebra is the most practically consequential one - and suffice it to say, it’s not a coincidence that BLAS, LINPACK, and LAPACK were all written in one-based languages. Matrix indexing is one-based, and beyond the issue of translating notation from equations, IIRC there is even a slight performance difference in some cases. I believe what it really comes down to is that, just as zero-based really is more natural for offsets (zero offset means the first position, great for pointers), one based really is more natural for counting [and _sets_] (when your index is n that means you have counted n elements up until now).