r/programming • • Nov 09 '15

E.W. Dijkstra Archive: Why numbering should start at zero

https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
935 Upvotes

437 comments sorted by

143

u/EllaTheCat Nov 09 '15

Years ago, pre internet, these circulated as photocopies of handwritten originals. His handwriting was beautiful. Then someone showed you the one he wrote with his other hand for practice, which was just as perfect to look at.

203

u/mayankkaizen Nov 09 '15 edited Nov 09 '15

I came across this article via Fluent Python written by Luciano Ramalho. He said in his book, "Somebody should create a Dijkstra font. I’d buy it."

Edit: https://joshldavis.com/2013/05/20/the-path-to-dijkstras-handwriting/

11

u/Meguli Nov 09 '15

http://lucacardelli.name/indexartifacts.html

Luca Cardelli did that long time ago I think. He has a ttf EWD font here.

3

u/tincholio Nov 09 '15

http://lucacardelli.name/indexartifacts.html

Is there anything Luca hasn't done? The guy's got a really impressive mind!

1

u/mayankkaizen Nov 09 '15

Awesome guy. How come he isn't that famous? Or may be I am too ignorant to have known him.

→ More replies (2)

2

u/mayankkaizen Nov 09 '15

Cool.. Thanks for sharing that.

→ More replies (1)

34

u/885895 Nov 09 '15

For those who didn't notice, the page you linked in your edit links a Dijkstra font. http://www.fonts101.com/fonts/view/Uncategorized/34398/Dijkstra

54

u/smapti Nov 09 '15

My God, that is truly beautiful! It's interesting that he didn't do what most of my math profs taught me, which is to edit handwriting for purposes of functionality. For example, to differentiate 't's from addition and 'i's from semicolons, '1's from lowercase 'l's and 'z's from '2's. Functionality has informed a significant portion of my handwriting but after seeing Djikstra's I wonder if it was worth it.

38

u/SushiAndWoW Nov 09 '15

Functionality has informed a significant portion of my handwriting but after seeing Djikstra's I wonder if it was worth it.

It is worth it. Perhaps you haven't developed beauty as much as function, but the two are not at odds. You can have both.

20

u/smapti Nov 09 '15

I certainly agree in principle! Here is the best I could manage in college while maintaining no ambiguity, and it's become my permanent handwriting. I would love to see others'

7

u/philly_fan_in_chi Nov 09 '15

Don't forget lower case q <-> 9! I cross my q stem to get rid of that ambiguity.

→ More replies (7)

5

u/Kiloku Nov 09 '15

The only thing that bothers me is that it's big. Using bigger handwriting is usually misinterpreted as laziness.

4

u/[deleted] Nov 09 '15

I hardly write at all. Do I win?

6

u/Dafuq_McKwak Nov 09 '15

The Path to Dijkstra’s Handwriting

My class in algorithms pays off with dividends.

8

u/timeshifter_ Nov 09 '15

Holy shit. I've been reading and/or interneting for... shit, how old am I? 23-ish years now. I'm fairly well inebriated at 5am right now... and not only did I have zero difficulty in reading that image.... I absolutely flew through it. As in... I don't think I'd interpret Verdena faster than that while sober. Why is that so readable?

3

u/ReinH Nov 09 '15

It's extremely consistent. The biggest factors are the straight baseline and consistent letter- and word-spacing, but the rounded bowls and counters and relatively large x-height also play a factor. The letter shapes are extremely consistent as well.

If you slow down your handwriting and focus on baseline and spacing consistency, you'll see a big improvement no matter what your letters look like.

24

u/robinhouston Nov 09 '15

I still find the handwritten version easier to read.

10

u/jdgordon Nov 09 '15

as nice as his handwriting is, his english doesn't make for easy reading

19

u/[deleted] Nov 09 '15

His Dutch isn't that easy to read, either.

2

u/MacASM Nov 09 '15

as a non-native speaker and with bad English, are you saying his English bad or good?

5

u/likesdarkgreen Nov 09 '15

Dijkstra has good English. It's just a little harder to understand since it's not how most people speak naturally so it takes extra effort to understand because native speakers are not used to certain phrasings. This happens a lot even with two native speakers in technical writing if they study different fields.

→ More replies (2)
→ More replies (4)

5

u/[deleted] Nov 09 '15

I find the beauty of his handwriting distracting from the subject under discussion.

1

u/CarVac Nov 09 '15

Interesting that he hyphenates words across line breaks.

1

u/oh-just-another-guy Nov 09 '15

Looks like he did not like cursive.

16

u/Workaphobia Nov 09 '15

Sometimes students will say they understand how to code an algorithm but keep getting off-by-one errors. But if you are off-by-one, you don't really understand. If you don't know whether your bounds are inclusive or exclusive, or whether the length is your endpoint minus your start point or one more or less, then you're not thinking clearly enough. You're just guessing and hoping the machine will back you up.

Dijkstra was trained in an era where you sent your code off to run and waited days for the response. If you had a bug, you wasted a lot of time. He knew his code worked before he ran it because he thought about it thoroughly instead of incidentally.

His argument makes perfect sense, and it comes from a source we have reason to trust.

7

u/mayankkaizen Nov 09 '15

True. These days, people, including me, tend to code without mentally imagining how that code would run. We don't worry about hardware limitations these days. With plenty of memory and fast processors at our disposal, we forget to appreciate how hard it was to run a code back then. Sometime I feel students should be forced to interpret their program line by line without executing. I tried it and it is really hard.

Some of old time programmers would tell me that they learned programming by writing code on papers and imagining how would it run. Having access to computers was something which was extremely difficult.

5

u/mcguire Nov 09 '15

Dijkstra was trained in an era where you sent your code off to run and waited days for the response.

Technically, Dijkstra was trained in an era where, if you wanted your computations run by a machine, you started by building a machine.

4

u/playaspec Nov 09 '15

If you don't know whether your bounds are inclusive or exclusive, or whether the length is your endpoint minus your start point or one more or less, then you're not thinking clearly enough.

This single sentence really crystallized the way I will evaluate bounds tests from now on. Thanks.

2

u/Workaphobia Nov 09 '15

Great! Now go out there and code binary search, and get it right the first time!

617

u/flip314 Nov 09 '15

"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." - Stan Kelly-Bootle

518

u/travia21 Nov 09 '15

I first read that joke while I was doing homework in a java class. I started a for loop at .5, then included the quote on the same line. I was awarded with half a point taken off of my grade for poor design, and half a point of extra credit for good documentation.

91

u/[deleted] Nov 09 '15

They actually read your code and gave you feedback? I don't think that's ever happened to me.

24

u/Ole_Gooner Nov 09 '15

Agreed. Most of our assignments were just run through something that checked for copying.

It didn't work when you added random numeric strings to the end of variables though.

17

u/murkwork Nov 09 '15

Pfft seriously? The guy that wrote the copy checking program couldn't be bothered to do a "contains" check instead of an "equals" check? That's the dude responsible for teaching proper programming practices? Sheeeeet.

47

u/forgottenduck Nov 09 '15

It's probably just some code he found on the internet and copy/pasted in.

→ More replies (5)

2

u/Tasgall Nov 09 '15

Ha, you (rather, anyone who did that) would have been thrown out of my CS classes on the first assignment. The prof ran everything through a custom minifier he wrote before diffing. None of your variable names were even in the code he checked.

6

u/covercash2 Nov 09 '15

It just occurred to me that all my college programming projects were graded pass-fail, and we never did code reviews.

4

u/SeraphLance Nov 09 '15

I had a college professor who would only take projects (one of which was a full-blown compiler) in printed paper.

We got all of them back with marks throughout the submission. It was pretty terrifying.

→ More replies (1)

6

u/TheFeshy Nov 09 '15

I got one back that was just a giant interrobang covering the whole printed assignment. Is that feedback?

To be fair, it was our "hello, world" assignment in basic, and I output a bitmap of "hello, world" to the framebuffer (and included the bitmap as an array (or whatever passed for one in basic) in my program so that it would be self-contained. In my defense, the school wouldn't let me start programing classes until my Jr. year in High School.

0

u/[deleted] Nov 09 '15

[deleted]

5

u/dynoraptor Nov 09 '15

That's actually a test to see if you're autistic. If you don't recognise it's a joke, you test positive for autism.

4

u/TheFeshy Nov 09 '15

My highschool did not excel at computing.

Our high school's programming section was taught by the business teacher, if that gives you an idea. She gave extra credit for wearing a tie. Let's just say that my bored highshool self found avenues of release through that class, which should have been one I loved but was instead "suit and tie"... and as a result that was her last year teaching.

2

u/whiznat Nov 09 '15

Does "Wow you really blew it" count?

2

u/morcheeba Nov 09 '15

We even got that in EE. I had an intro-level embedded systems class and I'd been doing the stuff already for 3 years... they said to optimize a program, expecting people to improve it 1-3%. I used some serious cheats to keep it barely functional while I made it 10x faster and the grad student checking it didn't even blink an eye :-(

→ More replies (1)

0

u/[deleted] Nov 09 '15

[deleted]

0

u/[deleted] Nov 09 '15

[deleted]

→ More replies (6)

38

u/bugrit Nov 09 '15

0.5 is the first index of a 1D texture on most graphics hardware/shaders.

63

u/theeth Nov 09 '15

It's the center of the first texel, to be precise.

18

u/bugrit Nov 09 '15

Well I suppose the index is really [0,1) if we're being precise, but it's 0.5 that would sample as the texel value with linear filtering.

10

u/theeth Nov 09 '15

Quite so.

You'll probably want to turn off filtering if you need exact texel sampling (for post process effects for example) but that's a bit beside the point.

9

u/[deleted] Nov 09 '15

Unless you're DirectX 9.

6

u/tobias3 Nov 09 '15

Yes, and it really is fun if you forget/don't know this is the case when you are programming something with 2D-matrices in texture buffers in CUDA.

3

u/bilog78 Nov 09 '15

Yes, and it really is fun if you forget/don't know this is the case when you are programming something with 2D-matrices in texture buffers in CUDA.

That only happens if you're using a texture with (bi)linear interpolation enabled, and if you do that for a matrix you deserve what you get.

2

u/tobias3 Nov 11 '15

It was for an image processing task where we needed the interpolation.

→ More replies (1)

5

u/dangerbird2 Nov 09 '15

OpenGL considers fragments(pixels) and texels to be areas, rather than discrete points in memory, so it makes sense that it indexes by midpoint.

11

u/[deleted] Nov 09 '15

Kinda reminds me of Randall Munroe's intro to the UK version of What If and the "compromise foot" (average between 1m and 1ft)

1

u/Grazfather Nov 09 '15

'middle ground' logical fallacy ;)

0

u/[deleted] Nov 09 '15

[deleted]

13

u/laxatives Nov 09 '15

I think there's a fairly famous Physics paper by a well known professor that has a body that consists of the single word "No." and a very verbose title along the lines of "Does Y indicate X?"

18

u/vks_ Nov 09 '15 edited Nov 10 '15

It was not the body, only the abstract. (I don't think such a short paper would be accepted anywhere.)

The paper was about the allegedly faster-than-light neutrinos and written bei a Noble prize winner (source).

37

u/travia21 Nov 09 '15

So... can someone break down what the second paragraph means? The language is a bit arcane. I get that he's dialing in to option A, but how? What does

Exclusion of the lower bound forces for a subsequence starting at the smallest natural number the lower bound as mentioned into the realm of the unnatural numbers.

or

Consider now the subsequences starting at the smallest natural number: inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one.

mean?

55

u/Sniffnoy Nov 09 '15

Exclusion of the lower bound forces for a subsequence starting at the smallest natural number the lower bound as mentioned into the realm of the unnatural numbers.

If you use a style where you list a lower bound that is excluded from the subset you are describing -- for instance, 1 < i <= 12 -- then to describe a subset starting at the smallest natural number, you would need to use a lower bound even smaller. This would force you to use something other than natural numbers in your description.

Consider now the subsequences starting at the smallest natural number: inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one.

If we use a style that includes both the lower and upper bounds, then we have no way to write the empty set in this style.

5

u/travia21 Nov 09 '15

Thank you.

9

u/[deleted] Nov 09 '15

If we use a style that includes both the lower and upper bounds, then we have no way to write the empty set in this style.

That's not exactly what Dijkstra is saying. Sequences starting at the smallest natural number can generally be denoted 0 <= i <= n (taking 0 to be natural). This sequence has length n+1, so when it has length 0, it ends up being denoted 0 <= i <= -1, which works, but looks very strange.

2

u/agcwall Nov 10 '15

And if you have a language which supports unsigned integers, this kind of comparison will fuck you. All unsigned ranges should be representable using only unsigned numbers and unsigned comparisons.

→ More replies (1)

4

u/caltheon Nov 09 '15

Why not? 1 < i < 0

6

u/[deleted] Nov 09 '15

That expression never matches, so it's incapable of representing anything other than the empty set. An optimal solution would use the same test for items within and without the set.

5

u/[deleted] Nov 09 '15

An optimal solution would use the same test for items within and without the set.

If the goal is to represent the empty set using either a < i < b or a <= i <= b, then /u/caltheon's solution does it fine. It trivially uses the same test for "items within and without the set", as there are no items within the set. The problem is only that it looks ugly.

6

u/emn13 Nov 09 '15

Well, it's also going to make the algorithms for shrinking a range complex.

Also, it depends on the circumstance, but "normal" ranges aren't exactly sets. Whether it's a good idea to exploit this is another matter, but that means it's not entirely clear whether all empty ranges should be considered equivalent. Certainly the set of values they contain is equivalent, but you might ask of a range why a value isn't included - is it too low or too high? Or your api might allow extending ranges by appending (or prepending) the next logical value. Depending on the details of what you want the range api to be, there may well be observable differences between [0, -1] and [1, 0]. /u/caltheon's solution may or may not be valid, depending on the details.

→ More replies (1)
→ More replies (1)

1

u/isarl Nov 09 '15

If we use a style that includes both the lower and upper bounds, then we have no way to write the empty set in this style.

...without likewise using something other than natural numbers. You can express the empty set by saying 0 ≤ i ≤ -1, as there are no values for which the expression holds, but using -1 as an upper bound is weird. The argument is essentially that 0 ≤ i < 0 is a neater way of denoting the empty set.

19

u/emn13 Nov 09 '15 edited Nov 09 '15

I'll take a stab at explaining the first comment, i.e.

Exclusion of the lower bound forces for a subsequence starting at the smallest natural number the lower bound as mentioned into the realm of the unnatural numbers.

His example used the range of numbers 2,3 .. 12. That's easily expressible regardless of your style. However:

(a) Imagine you include 0 in the natural numbers (a matter of some debate) and

(b) imagine you want a subsequence starting at 0; e.g. 0,1..12

Then if your lower bound style preference is exclusionary (i.e. < as opposed to ≤) then how are you going to write that subsequence?

Well, you'd need to write -1 < i ≤ 12. And that's ugly in the sense that to describe a natural number range you now need values outside of the range of natural numbers. And it's impractical on a computer since that means we'd need to represent this sentinel "-1" value which is out of bounds, which thus cannot be the same representation as that of the number (assuming the number representation doesn't waste space).

Now, he doesn't explicitly say what the lowest natural number is possibly because there's some debate as to how to define a natural number. But if you look at the above argument, you'll see that if you start numbering at 1 instead of 0, you run into the same problem: an exclusionary lower bound means that to include the smallest number you need to be able to represent numbers outside of the range you're dealing with.


The second comment is kind of the same:

Consider now the subsequences starting at the smallest natural number: inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one.

If you accept that the lower bound should be inclusionary, not exclusionary, well, why not the upper bound too?

Suppose you have such a range: [0 .. 12]. Then in many cases you're going to want to shrink that range; e.g. in a binary search. And shrinking down to 1 element is fine: [0 .. 0] but if you want to shrink any farther (i.e. make it empty) you'd need to write [0 .. -1] and that's pretty ugly. It also has the same practical problems that -1 did in the previous case: it's out of range, so that means your subsequence representation of numbers must differ from your normal representation of numbers (if said representation is optimal).

So this particular argument against an inclusionary upper bound concerns the undesirability of needing an out-of-range number (-1) to denote the empty range starting at zero.

4

u/qevlarr Nov 09 '15

Exclusion of the lower bound forces for a subsequence starting at the smallest natural number the lower bound as mentioned into the realm of the unnatural numbers.

If you want the smallest natural number 0 as your smallest index and you write lb < x (instead of '<='), your lower bound should be -1, which is not a natural number anymore.

Consider now the subsequences starting at the smallest natural number: inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one.

If you write 0 <= x <= ub and you shrink the list until it becomes empty, then ub=-1 which is not a natural number.

2

u/ledasll Nov 09 '15

Or in other words, you have limit on one side (zero) and no limit on another side (infinity), so you do equal where you have a limit and leave wide open, where you don't have.

26

u/rydan Nov 09 '15

Don't buildings in Europe start at floor 0?

50

u/vanderv Nov 09 '15

Yes, but we call it the "ground floor."

10

u/rydan Nov 09 '15

In America we do the same but the floor above it is 2. And the floor below it is B or B1 if there are multiple.

12

u/vanderv Nov 09 '15

Ah right. I wonder why you don't start at B2 as well.

The numbers in a lift here are G, 1, 2, 3... and -1, -2 for underground.

11

u/-_-_-_-__-_-_-_- Nov 09 '15

Because it's the first basement. The numbers follow the naming convention, not the other way around.

Ground floor is often called the first floor. It is G or 1. Above the first floor is the second floor, etc.

And below the ground level is the first basement.

5

u/[deleted] Nov 09 '15

What? Really? So, you don't have a first floor?

That sounds really confusing!

16

u/tszigane Nov 09 '15

If you gave the ground floor a number it would be 1. People use first floor and ground floor interchangeably.

5

u/[deleted] Nov 09 '15

Ah, so you might call what I'd call the ground floor, the first floor.

Shows how hardwired these things get - I'd assumed the numbering went B2, B1, 0, 2, 3 etc!

→ More replies (4)
→ More replies (1)
→ More replies (2)

9

u/madaal Nov 09 '15

Where I live, yes but we don't use the term "floor 0" it has a special name, in french : "rez de chaussée"

6

u/RandomDegenerator Nov 09 '15

In Germany, it's sometimes called "Parterre".

4

u/tszigane Nov 09 '15

I thought parterre was for when the entry level was raised up compared to the ground. I only ever hear Erdgeschoss otherwise. I'm not a native speaker.

2

u/RandomDegenerator Nov 09 '15

It's more of a regional thing, really. Most people say Erdgeschoss nowadays, but especially down south, Parterre is frequently heard. When the entry level is above ground, some even refer to it as a Hochparterre.

2

u/LordOfBones Nov 09 '15

And in Dutch it is just called "begane grond". Parterre is rarely used in Dutch.

7

u/vanderZwan Nov 09 '15

Depends on the nation. Sweden is one of the few countries who don't, and this leads to much confusion for exchange students in the beginning of their studies (speaking from personal experience). Some buildings circumvent this by starting with floor A and work their way up the alphabet, leading to equal confusion for all.

3

u/emn13 Nov 09 '15

How egalitarian ;-).

2

u/bik1230 Nov 09 '15

I have never seen a building in Sweden that doesn't start at 0, or "B" (bottom floor).

2

u/vanderZwan Nov 09 '15

Maybe it's region dependant? I've lived in Malmö for a while.

1

u/stronghup Nov 09 '15

Sweden makes me think, wouldn't it be better if we said if you need to walk up one set of stairs to your home you live on CEILING 1. If you live on "ground-floor" meaning you live on the ground, you live on CEILING 0. Which of course is not a ceiling at all, which just means CEILING 0 does not exist. Assuming we don't count underground things which are negative numbers. When you're in basement you are on CEILING -1.

11

u/genghisdani Nov 09 '15

To the best of my knowledge, they do - and Israel (where I live) numbers similarly. The problem with this is that you end up with a building of N floors, with the highest floor being numbered N-1. On the other hand, the European convention of counting rooms in a house instead of bedrooms (as in America) makes a lot more sense; if you have a studio apartment, it is an apartment with a single room - not 0 bedrooms.

I suppose the bottom-line is that 0-numbering really doesn't work well in real life.

15

u/Nomto Nov 09 '15

But for elevators it works well then, you get something like:

3
2
1
0 (groundfloor, RDC, whatever)
-1 (lower ground floor)

12

u/ThisIs_MyName Nov 09 '15

if you have a studio apartment, it is an apartment with a single room - not 0 bedrooms

That's because you're actually counting. Rather than describing a position.

5

u/emn13 Nov 09 '15 edited Nov 09 '15

I'm not sure I see the problem. So a building has e.g. floors 0,1,2,3,4 - which is in total 5 floors. How is this supposed to confuse people in "real life"? I've never seen that happen (I live in the netherlands). People rarely bother to consider how many floors a building has in the first place.

In common dutch practice a verdieping usually corresponds to an additional floor, i.e. a building with 5 floors has 4 verdiepingen 1,2,3,4 in addition to the ground floor. A building with only a single floor has no verdieping. In practice that may explain the lack of confusion - you could say it's numbered in (0, N] style ;-) and 0 or lower are special-cased. Of course, this being natural language, there are fuzzy exceptions.

8

u/ethraax Nov 09 '15

Intuitively, when a building has 30 floors, people around here expect there to be a floor 30.

Also, basement floors are not counted.

7

u/emn13 Nov 09 '15 edited Nov 09 '15

Well, here (NL) they changed the definition of "floor" to exclude the ground floor. They're "extra floors" if you will. And if a building has 30 extra floors, it indeed will have a button 30 in the elevator (and would have at least 31 floors in the US sense).

But... even if people counted floors like in the US - people don't actually think "hey, there are 30 floors, what is the top floor #". They know they need to go to floor 30. Whether they realize that means there are 31 floors or not doesn't pose a problem in real life. That's more like a pubquiz kind of problem, not a real world problem. In the real world, 0 numbering works quite well.

Not that I'd consider this to be a real problem, but floor numbering around 0 makes taking flights of stairs slightly easier. How many flights of stairs do you need to ascend to go from -2 to 2? In the 0-centric worldview, that's plain subtraction. In the US, off by one would lead you into uninitialized floor territory, triggering undefined behavior, which can include side effects such as ending up in willy wonka's chocolate factory :-).

Unless you're a building contractor, I don't see the relevance to most people of how many floors a building has nor of what precisely the definition of a floor is. If anything it's a tiny bit easier to use 0 in practice if there are basement floors in play. It may make calculating how high you are slightly easier. Which approximately 0% of the populace ponder daily. And that's about it.

In other news, birthdays are oddly numbered as well, because on your first birthday, you've had two birthdays: the one you're celebrating, and the day you were actually been born. Yet the world blithely proceeds :-P...

4

u/ethraax Nov 09 '15

Yeah but I didn't get cake on my zeroth birthday.

→ More replies (3)

7

u/vinnl Nov 09 '15

In my country, the top floor is zero and we count up until we get to the bottom floor. Thus, the basement is <ground floor number>+1.

Source: I lied.

6

u/[deleted] Nov 09 '15

In my country, floor numbers are the square root of the offset from floor -6 multiplied by pi. Except for the second basement floor, which is affectionately known as BONGO BONGO.

2

u/notjustaprettybeard Nov 09 '15

In the UK the first floor is up one flight of stairs but the level below is the 'ground floor' and never 'floor 0', which is probably the worst of all possible worlds.

1

u/Amuro_Ray Nov 09 '15

Kinda. It's how many floors above ground.

1

u/xtracto Nov 09 '15

In Mexico too! PB, 1, 2,3 ...

1

u/Tarmen Nov 09 '15

Yup, although it usually isn't called floor 0. Probably translates to something like ground floor or earth floor mostly?

Some buildings just want to do their own thing, though. Know a university where room numbers go building.room_index.area.floor for instance and floors are 1-indexed because technically there are secondary doors on floor zero that lead to pretty much nowhere :/

10

u/oconnor663 Nov 09 '15 edited Nov 09 '15

Thought experiment: what if we numbered starting with 1 and used inclusive-on-both-ends ranges?

The range(n) function would still have nice properties. Range(0) would be an empty set, range(1) a set of size 1, and so on. It seems all the downsides have to do with specifying ranges with two numbers, but how often do we do that?

Edit: I guess in C we always do that. But this doesn't seem so bad:

for (int i=1; i<=N; i++)

33

u/[deleted] Nov 09 '15

Suppose I've got a 3x3 matrix, stored internally as an array of nine numbers.

With 0-based indexing, the index of the (row, column) element could be row * 3 + column.

With 1-based indexing, it's (row - 1) * 3 + column. The fact that I've got an extra -1 in there isn't that huge of a deal, but note that we had to subtract 1 from one index but not from the other -- this sort of thing is really easy to screw up and ends up causing a lot of off-by-one errors.

Now, of course you could argue "just use a 2-dimensional array!", and that's a valid point in this simple case, but it doesn't remove the unnaturalness; it just hides it from you. You will run into other real-world situations where you cannot hide it.

Both zero- and one-based indexing have their faults. In both cases you end up with the occasional adjustment by 1 to avoid off-by-one errors. However, decades of experience show that 0-based indexing leads to far fewer adjustments than 1-based indexing, and those adjustments are tougher to screw up.

6

u/oconnor663 Nov 09 '15

I hadn't thought of that example. Good point.

1

u/oantolin Nov 10 '15

but note that we had to subtract 1 from one index but not from the other

Well, you could treat rows and columns more symmetrically and write (row-1)*3 + (column-1) + 1. This generalizes to more than two indices, for example in a 3x3x3 matrix the 1-based position (i,j,k) is stored at (i-1)*9 + (j-1)*3 + (k-1) + 1.

→ More replies (2)

9

u/randomguy186 Nov 09 '15

Counting discrete quantities starts at one because throughout human history that's how it's been done. Measuring continuous quantities starts at zero because throughout human history that's how it's been done. Trying to change how something has been done for thousands of years invites error.

Measuring a set that doesn't fit neatly into one of those two categories doesn't really have a deep historical precedent. Expecting all measurements to fit neatly into one of those two categories sets invites error.

4

u/hoijarvi Nov 09 '15

Yep. I suggest we should compromise with 0.5 to be fair to both camps.

5

u/mcguire Nov 09 '15

You number chauvinists are all the same. Your 'counting' and 'measuring' will never constrain the human spirit!

Array indexing should start with elbow. The next element, what you heathen numberists would call "second" should be walnut, followed by blowfish. There's never a need for anything more.

5

u/shizzy0 Nov 09 '15

How fast is your algorithm?

O(foot)

2

u/mcguire Nov 09 '15

Now I'm going to spend all evening trying to come up with an interpretation for that that's reasonable.

→ More replies (1)

7

u/MpVpRb Nov 09 '15

Counting is different from using numbers to represent distance

Counting starts from one..1,2,3... I have three objects

Distances start from zero..If I am standing in front of my house, how far do I need to walk to stand in front of my house?

If my pointer points to the first element of the array, how far do I have to move it to point to the first element of the array, how far to the next element?

Indexing in software is distance, not counting

1

u/mayankkaizen Nov 10 '15

Addition: Here is what Guido van Rossum (Python creator) had to say about why Python uses 0-based indexing.

21

u/jnicklas Nov 09 '15

The problem with this essay is that it establishes a very nice line of reasoning as to why a certain representation of ranges is preferable, but that is not the title. The title is "Why numbering should start at zero", and IMO Dijkstra completely fails to establish his argument for that statement. Let's look at the key section:

Adhering to convention a) yields, when starting with subscript 1, the subscript range 1 ≤ i < N+1; starting with 0, however, gives the nicer range 0 ≤ i < N. So let us let our ordinals start at zero: an element's ordinal (subscript) equals the number of elements preceding it in the sequence.

The first sentence is obviously completely subjective. Why would one range be nicer than the other? Because it contains N+1? That's subjective. There is nothing objectively better about this range. He doesn't establish any objective argument in this sentence at all, other than his personal preference. I find the other range "nicer", how are you going to prove that I don't?

As for the second sentence, the argument is completely silly.

So let us let our ordinals start at one: an element's ordinal (subscript) equals its position in the sequence.

What now, Dijkstra?

6

u/chewitt Nov 09 '15 edited Nov 09 '15

Exactly. Here's another "nice" range: 0 < i ≤ N

With THIS arbitrary range convention, all his logic supports starting at 1.

1

u/stronghup Nov 09 '15

Agreed. If there is one element in a set, its size is 1, and we call the only element the 1st element, and we refer to it as the 1st, and why not drop the 'st' from that to make the reference even shorter.

If there is 0 elements, there is no 0th element of course, and the size of the set is 0.

When we write all these facts down we never need to use the + or - signs, which means we never need to use arithmetic calculations to make sure what we are saying is correct. If you need to do a calculation (even if it is as simple as adding or subtracting 1) it is still a calculation and calculation can go wrong. You can't go wrong if you don't need to do any calculations, just remember the fact that the index of the 1st element is 1, and the size of the set is the SAME as the index of its last element.

2

u/mcguire Nov 09 '15

Agreed. If there is one element in a set, its size is 1, and we call the only element the 1st element, and we refer to it as the 1st, and why not drop the 'st' from that to make the reference even shorter.

Please don't mix your cardinals with your ordinals. You'll have a horrible time with the transfinite numbers.

1

u/stronghup Nov 09 '15

As further proof that using 0 makes things more complicated than they need to be consider that zero wasn't even invented before year 458. Zero doesn't exist in the sense that other numbers do, it had to be "invented".

http://www.livescience.com/27853-who-invented-zero.html

0

u/[deleted] Nov 09 '15

[deleted]

2

u/jnicklas Nov 09 '15

As I said: I follow his reasoning as to why the range representation a) is preferable, he builds a solid argument for that. The problem is that the jump from this to 0-indexing is completely unfounded.

Why is 1 ≤ i < N+1, which is represented using his preferred representation(!), not an acceptable range? He makes no good argument for that.

His argument about the N-preceding elements does not make any sense at all.

If we choose 1-based indexing, as I stated, you get n-1 preceding elements, and the element with index n becomes the nth element. This is a just as good, if not better argument. The n preceding element thing is just not useful at all in programming or reasoning. In real life, no one would say "ahh, the 3rd element, that means there must be three elements preceding it", that's nonsense.

There might be valid reasons to prefer 0-based indexing (in some languages at least), but in this essay, Dijkstra doesn't make a good case for it.

→ More replies (2)

10

u/Tweakers Nov 09 '15

Context is everything.

6

u/checkmatearsonists Nov 09 '15

Exactly. In a different context, different preferences may make sense. I've always enjoyed Lua's 1-based indexing because it made a lot of stuff easier to read and write, yet I wouldn't debate anyone on this because their project environment may have totally different technical prerequisites. If it works for you, then it's best.

7

u/[deleted] Nov 09 '15

Counting starts at 1. Measuring starts at 0.

1

u/TOGoS Nov 10 '15

Only after you've counted one full item does it. Before then you've got zero, just as you've got zero cups of water before you fill your cup with water.

1

u/findwedow Nov 11 '15 edited Nov 11 '15

Brilliant summary. I was going to talk about cardinal vs. ordinal numbering, which is what this is all about. It strange that these terms that were once were familiar to children are hardly seen in this discussion about them. Regardless, the term 'counting' and 'measuring' are much more meaningful. I am going to remember this.

I always think of zero-based indexing (cardinal, measuring) as pointing between items in a sequence, and one-based indexing as pointing to the item cell in the sequence. With this distinction in mind, I never have trouble with off-by-one errors.

The only tricky part is the zero-indexing languages always confuse things by letting the index identify the first item on the right. It is a sort of implicit type conversion from cardinal to ordinal.

I have always been a very big fan of Dijkstra, but he went overboard on this topic. One should never need the term zeroth.

13

u/i_have_seen_it_all Nov 09 '15

There will be no consensus on this issue. All math papers are written with 1-indexing. Math oriented languages will almost always do 1-index. Reference to the i-th element of a matrix m should never ever be m[i-1]. That will lead to awful off by one errors.

30

u/gct Nov 09 '15

It's just not true that mathematicians default to 1, they use whatever's convenient. The DFT is a good example, where they usually start with zero, because it's handy to have a zero-bin in the frequency domain that corresponds to zero-frequency (DC). Sometimes they even start with gasp negative indices.

5

u/[deleted] Nov 09 '15

They're anarchists, I tell you, anarchists!

Swapping out notation for convenience.

Why won't the embrace the One True Interval?

(As a serious aside, 0-based indexing makes python slices and strides so much cleaner to reason about. That to me is a good argument for 0-based notation if you use slices/strides)

2

u/ffp12 Nov 09 '15

As it should be.

4

u/chrisdoner Nov 09 '15

It's the same for columns in editors and compilers. Cursor at the start of the line in Emacs is column 0. SublimeText calls it column 1. Compilers vary on the indexing scheme for error messages they output.

2

u/TexasJefferson Nov 10 '15

Reference to the i-th element of a matrix m should never ever be m[i-1]. That will lead to awful off by one errors.

This is just an argument for changing linear algebra's notation. :-)

3

u/Patman128 Nov 09 '15

FORTRAN and MATLAB both use 1-based indexing, so I can see why it would be the norm in some circles.

Reference to the i-th element of a matrix m should never ever be m[i-1]. That will lead to awful off by one errors.

I'm personally a fan of 1-indexing for this reason. 0-indexing only makes sense in the context of C's pointer-based arrays.

1

u/G_Morgan Nov 10 '15

Until mathematicians embrace the might of τ (tau for the illiterate) I feel safe ignoring their opinions.

1

u/origin415 Nov 10 '15

N-dimensional projective space involves N+1 variables, which are usually written x_0, ... x_N. That's the only example I regularly see in mathematics.

3

u/masuk0 Nov 09 '15

Used to write in C# for COM API created for visual basic scripts. This was driven me mad.

3

u/Gubru Nov 09 '15

For anyone else wondering about his signature and that ij that looks like a ȳ, I found this discussion helpful.

1

u/mcguire Nov 09 '15

I have no joke, I just like saying, "Plataanstraat".

3

u/IDe- Nov 09 '15

OP: "Because then a repost is actually the first post."

3

u/protonfish Nov 09 '15 edited Nov 09 '15

He makes a good point, but it is based on redefining a sequence without "the pernicious three dots". What I don't understand is why those dots are so bad. That notation is unambiguous to humans, so why don't we just include something like "3-dot format" in a computer language?

3

u/[deleted] Nov 10 '15

The difference between mathematicians and computer scientists (and I am speaking very generally) is that mathematicians care about the bounds on a variable and the number of things in a set, while computer scientists care about how many times they will do something and how far they are from where they started (e.g. list indexing). Hence the two different conventions on bounds and numbering.

13

u/armornick Nov 09 '15 edited Nov 09 '15

Even "better" than fixed subscripts would be the system I've seen in some languages where you can do array[0 .. 5]. So you can choose at which number your array starts and there's no ambiguity of the last index of the array. Don't remember the exact syntax or which language it was, though.

In the end, I feel like it doesn't really matter. 0 indexing has a wider adoption, while 1 indexing is more in line with how people think (supposedly, though I don't know anyone who starts counting at 0).

The argument that [0, n-1] is nicer than [1, n] is silly, though.

23

u/emn13 Nov 09 '15 edited Nov 09 '15

I believe you're referring to the argument that [0, n) is nicer than [1, n+1). Seperately, half-open ranges are preferable because they avoid off-by-one errors in length computations and make computing adjacency trivial. That's why [0 .. 5] isn't such a hot idea. Notably your own example makes this mistake: [0, n-1] isn't isomorphic to [1, n+1]! (After posting this, the comment parent was fixed. In any case, by dijkstra's logic, if you were to pick a closed interval in that style, [1..n] would be fine - but don't use closed intervals).

Anybody who's ever written a bunch of for loops must have come to pretty much these conclusions; certainly the advantage of half-open intervals is entirely practical.

1

u/Tarmen Nov 09 '15 edited Nov 09 '15

I kind of like the notation Nim has where you can use 0..5 and 0..<5 for inclusive usage and exclusive ranges respectively. So you can just do

for i in 0..<array.len:
    discard

In that case you'd probably do

for i,j in array:
    discard

Arrays have their ranges as part of their type and default to being zero indexed, though, so I guess that doesn't matter much. It also all translates to mostly the same while loop but you get the idea.

12

u/st33d Nov 09 '15

I was on board with the fact that starting at any arbitrary value is simply a matter of preference. It's just a small mental shift.

Then I was making an on-screen grid with draggable tiles in Lua. That's when I started shaking my fist at the screen.

12

u/jdmulloy Nov 09 '15

Starting arrays at 0 makes a ton of sense from the perspective of a language like C where an array is really a pointer to some memory and the index is just an offset. The first element has no offset and element N is P+N*sizeof where P is the pointer to the array.

5

u/gdwatson Nov 09 '15 edited Nov 10 '15

I have to imagine that languages which require the programmer to give the lower subscript have a convention that applies to most arrays. To mix 0-based and 1-based arrays at random is a recipe for gratuitous off-by-one errors.

This is one of those areas where local convention is almost always more important than personal preference.

Edit: Fix gratuitous typing error.

6

u/aaptel Nov 09 '15

[ 1, n ]

FTFY

20

u/emn13 Nov 09 '15 edited Nov 09 '15

...thus proving dijkstra was right. Don't use closed intervals because off-by-one errors are a thing.

Edit for context: the now-fixed comment originally included the following line:

The argument that [0, n-1] is nicer than [1, n+1] is silly, though.

3

u/Sean1708 Nov 09 '15

I don't really understand how closed intervals are more prone to off-by-one errors?

17

u/emn13 Nov 09 '15 edited Nov 09 '15

What's the length of a closed interval? When are two closed intervals adjacent? When is an interval empty?

→ More replies (7)

5

u/[deleted] Nov 09 '15

Because the length of a closed interval is end - start + 1 rather than the simpler end - start for an open interval.

It may seem fairly trivial in that case, but once you combine a few intervals with arithmetic it turns into quite a mess.

→ More replies (13)
→ More replies (1)
→ More replies (1)

2

u/_F1_ Nov 09 '15

Even "better" than fixed subscripts would be the system I've seen in some languages where you can do array[0 .. 5]. So you can choose at which number your array starts and there's no ambiguity of the last index of the array. Don't remember the exact syntax or which language it was, though.

http://wiki.freepascal.org/Array

3

u/log_2 Nov 09 '15

Oh god no! That is terrible! Imagine the chaos when different libraries and different programmers adopt different conventions. When writing a piece of software you would forever be switching contexts between 1 and 0 based indexing, rather than maintaining a uniform context for the language you're using.

1

u/MrBester Nov 09 '15

Option Base 1

1

u/mrbaggins Nov 09 '15

Shouldnt your last one just be [1,n]?

1

u/memoryspaceglitch Nov 09 '15

I think you might be thinking of Ada, where you define the range as you define the array.

See https://en.m.wikibooks.org/wiki/Ada_Programming/Types/array

1

u/[deleted] Nov 09 '15

Ada, Pascal or any language from that family for the most part.

1

u/awesley Nov 09 '15

(supposedly, though I don't know anyone who starts counting at 0)

But we do that with the age of people.

1

u/smallblacksun Nov 10 '15

That is heavily dependent on where you are from. In Asia (and I believe parts of Europe) you are 1 year old at birth.

7

u/gperlman Nov 09 '15

While I understand the rationale, people are used to counting from 1, not 0. It's takes extra thinking to loop from 0 to the end of the array. If you're an experienced programmer it's not a problem but if you're not, it's not intuitive.

5

u/Birk Nov 09 '15

Nobody counts from 1. That would mean the first count would be 2. People count from 0, they just don't realize it.

4

u/gperlman Nov 09 '15

Ask someone to make a list of 5 things and they will start numbering the list at 1, not 0.

→ More replies (5)

10

u/log_2 Nov 09 '15

I wish the creators of Julia had read this.

19

u/vanderZwan Nov 09 '15

Make a fork. Call it Julio. Keep everything else the same.

8

u/wnoise Nov 09 '15

Juli0.

11

u/pure_x01 Nov 09 '15

Or create an advanced preprocessor in JavaScript that is webscale through microservices with native bindings using rust.

2

u/sigma914 Nov 09 '15

Was their reasoning not that matrix maths is more natural with 1 based indexing?

→ More replies (1)

3

u/flying-sheep Nov 09 '15 edited Nov 09 '15

Me too.

I think people shouldn't make languages “feel more natural” by starting indexing at 1.

The really natural thing is starting at 0, we just all learned to count wrongly.

C got it right: the 3rd of 5 apples shouldn't be the apple that ends after eating 3 apples, it should be the one that starts there. I.e. a range of length 1 starting at position 3 and ending at position 4.

However, “i ate the first four apples” means you ate apples 0, 1, 2, and 3.

9

u/ThisIs_MyName Nov 09 '15

we just all learned to count wrongly

No, counting still starts at 1. You just have to use 0-indexing for positions.

6

u/Birk Nov 09 '15

Counting starts at 0. If you start counting something, but there are none of them, whats the count?

→ More replies (2)

3

u/flying-sheep Nov 09 '15

true, for the common case:

“one” → “there has been one apple”

7

u/gct Nov 09 '15

No, counting starts at zero, you just don't say it out loud.

→ More replies (1)
→ More replies (3)

6

u/ks07 Nov 09 '15

One based indexing is why being forced to use Matlab is so horrifying

2

u/OneWingedShark Nov 09 '15 edited Nov 10 '15

I disagree with Mr. Dijkstra here, and we can put the argument like so:
When you are counting some items you start with 1, for the next you say 2, for the third you say 3; this gives a map where the number you used corresponds to the list's length when including that item. -- This also means that you don't have to throw away half your possible-indices (in 2's complement) just so that you can use < to test for "not-found" while searching; this is to say reserving 0 for the "it's not here" value seems more prudent.

2

u/mwscidata Nov 09 '15

Of course EWD is right. However, it takes 2 days to fully and properly explain 0-based indexing to raw students (C). It takes 2 minutes to illustrate 1-based indexing (Lua).

The invention of zero is one of the great steps in history. However, teaching is not a vast knowledge dump onto a tabula rasa. Learning is a bootstrapping process.

1

u/findwedow Nov 11 '15

With respect, I think you just don't know how to teach it.

With 0-based indexing, the index points to the divider between the cells in an array. The divisions include the front where there are zero items on the left, and the back where there are zero items on the right.

With 1-based indexing, index points to the actual cells. An array with five cells has five ordinal indexes and six cardinal indexes. This takes no more more than 10 minutes to explain.

1

u/mwscidata Nov 11 '15

Thank you. You've just made my point beautifully.

1

u/Gloinson Nov 12 '15

Enter: the pointer.

0-based-index: data at 0 is at pointed-to-adress + 0

We were talking C? You know, the language where pointers are used? The thingies that, 0 or 1 or 0.5-based indices aside, a bit difficult to understand, as far as I have been told by people having difficulties understanding them (I might have been one of them, but that's too long ago).

2

u/agenthex Nov 09 '15

For some function arguments, I prefer to index arrays starting at 1.

This allows me to use an unsigned integer to represent the index being passed to the function, and if I want to no-op the function or do some other special task with it, I can pass it 0 instead. This becomes a reserved condition, and it doesn't break the brain of someone who might need to read my code later.

12

u/emn13 Nov 09 '15

special cases like that are really bug-prone.

However, why not pass the maximum integer instead? If you're going to special case values, that at least has the advantage that you're generally less likely to use that by accident.

Also, make sure you name that constant...

6

u/buttercheesebread Nov 09 '15 edited Oct 20 '25

cake familiar political narrow alive exultant rain cable work summer

This post was mass deleted and anonymized with Redact

8

u/ThisIs_MyName Nov 09 '15 edited Nov 09 '15

Naw, the linter complains about magic numbers. Use my library:

package com.reddit.www.https.r.programming
import java.util.*;
/***
 * Anti-Magic
 * @author /u/ThisIs_MyName
 */
@SuppressWarnings("all") public strictfp class AntiMagic extends Object{
    public static volatile transient long serialVersionUID = new Random().nextLong();
    /* BEGIN FIELDS */
    @Deprecated protected static volatile transient int ONE = new Integer(1);   //First  
    @Deprecated protected static volatile transient int TWO = new Integer(2);   //Second  
    @Deprecated protected static volatile transient int THREE = new Integer(3); //Third 
    //FIXME add more as needed
    /* END FIELDS */
}

4

u/Lord_Naikon Nov 09 '15

Might want to declare ONE, TWO and THREE as final :). Also add some annotations for good measure. I suggest @Deprecated.

→ More replies (1)
→ More replies (3)

1

u/ffp12 Nov 09 '15

That is for kids and the infirm. Real men use pointers. :)

1

u/agenthex Nov 11 '15
int array[10];

and

int *array = new int[10];

are the same thing.

2

u/DavidM01 Nov 09 '15

Because intuitively we all number lists starting at zero...

Sorry EWD is approaching this from CompSci instead of the human perspective.

9

u/[deleted] Nov 09 '15

Well if you're ever wondering why the years 20xx are in the 21st century, except for the year 2000 which is actually in the 20th century, because the 21st century didn't start till 2001, then you know what to blame.

2

u/Patman128 Nov 09 '15

That there's no 0th century?

It seems strange at first, but when you realize the first century is the years from 1 to 99, it makes sense. It's literally the first hundred (or ninety-nine?) years.

4

u/[deleted] Nov 09 '15

Yeah, there's no 0th century, and also there's no year 0. The first century was from years 1 to 100. 2nd century started at year 101.

→ More replies (2)

1

u/DavidM01 Nov 09 '15

That has zero relation to what I was talking about. Time is measured in relation to something else. So 1 AD is 1 Year after Christ was born ( or thereabouts ). 1 AD is the First year following His birth.
Sort of like you call this the 9th All day Long, even though the 9th isn't complete until 23:59:59 tonight.

Our numbering system starts with one. How do I know? One is older than the number zero. He has taken a human concept (numbering things) and applied them to a CompSci topic and decided its the "right way".

3

u/[deleted] Nov 09 '15

You were talking about what's intuitive, I was pointing out how one-based counting leads to some unintuitive situations.

1

u/whiznat Nov 09 '15

So that I can accurately count the number of ways I actually care about <whatever> no matter what it is.

1

u/nealio1000 Nov 09 '15

Talk about preaching to the choir with this title.

1

u/ILiftOnTuesdays Nov 09 '15

This whole article is based on the presupposition that 0 is a natural number, and that that fact is actually important.

1

u/hoyfkd Nov 09 '15

That is some unreadable "I'm a scholar, look at how complicated my sentence structure is" BS.

Also, if I have one of something, I will stick to using 1, not 0. If I come in first, I am the first. When I cross, there will be 1 person across the finish line. 1 works better than 0.

0

u/[deleted] Nov 09 '15

Why start with zero? I'm number one, baby.