Hacker News new | past | comments | ask | show | jobs | submit login

In mathematics, both are common. For example, when working with polynomials or polynomial-like things, it is common to label coefficients starting with 0. E.g., a0 + a1 x + a2 x^2 + ...

The subscript on the coefficient then matches the power of x, letting you write the general term as ai x^i, which works out great when using capital sigma notation.

One the other hand, matrix rows and columns usually start from 1, so the elements on the top row are usually a11, a12, a13, ..., and the next row is a21, a22, a23, ..., and so on.

In an attempt to bring some unity to the two sides on this issue in programming, let me offer something that I'm sure everybody will be able to agree on.

Once upon a time I was implementing some mathematical code in C++. It was a mix of things from places where mathematicians would number from 0 and where they would number from 1.

I decided that the code would be clearer if the code looked like the formulas in the math papers they came from, which meant I wanted to use 0-based arrays in some places and 1-based in others.

Solution: I overloaded the () operator so that array(i) was a reference to array[i-1]. Then I could use 0-based or 1-based, depending on whether I was using a formula that came from a 0-based or 1-based area of mathematics.

Everybody agree that this was not a good idea?




Julia and Fortran, languages designed to be used for mathematics and high performance scientific computing, take a similar approach in the language itself and support arbitrary starting indices for arrays. Sometimes the math is just cleaner when the index starts at 0, or 1, or 2, or -1!

https://docs.julialang.org/en/v1/devdocs/offset-arrays/


Julia (normally 1-based), Polynomials package:

    julia> using Polynomials
    julia> p = Polynomial([1, 0, 2])
    Polynomial(1 + 2*x^2)

    julia> p[0]
    1
As long as it is domain specific and wrapped in custom types I don't really see an issue.


And of course there is C++ libraries to do the same. For example the blitz++ library. Negative indices to the left of element[0] are great for ghost zones in codes that do domain decomposition over different MPI ranks.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: