Comment

Comment by qsort

Article is mostly fine, but there's a point I vehemently disagree with: you should not, absolutely not translate math notation to code.

Math is equational and declarative. When you write:

  S = \sum_{i=1}^{100} (2i + 1)
you are declaring that we shall call S the sum of the elements of a certain set. You are not prescribing how this sum ought to be calculated: S is a pure value that doesn't depend on what practical operations you do -- be them on paper or on a CPU -- to actually find out what S is.

For example, using equational reasoning, we may write:

  S = \sum_{i=1}^{100} 1 + 2 \sum_{i=1}^{100} i = 100 + (100 * 101) = 101^2 - 1
Or, without computing anything at all, we may prove by induction that:

  (1) \sum_{i=1}^{n} (2i + 1) = (n + 1)^2 - 1
The base case is obvious, and to prove the inductive step it is sufficient to observe that indeed:

  (n + 1)^2 - 1 + (2n + 3) = n^2 + 4n + 3 = (n + 2)^2 - 1
From which it follows:

  S = 101^2 - 1
Tying math to code is more like tying your own hands behind your back.

All of this is basically an excuse to point out that the code for the product is wrong, the initial value should be 1 and not 0 (or, in general, your monoid identity).

parent qsort 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton