Naive Programming

I think that may always be the case, especially when the resulting program is a function of what I’m asked to do! I was instead considering how, give experience in mathematical reasoning and programming, one writes increasingly concise code.

Because of the intense usefulness of Maths in programming, I cannot grok my fellow students’ disapproval of the subject. One of the major ways my code has grown less naive is in the borrowing of mathematical concepts.

Naive:

// print the sum of numbers x through y.
int sum(int x, int y) {
  int s = 0;
  for (int i = x; i <= y; i++)
    s += i;

  return s;
}

Insightful:

// print the sum of numbers x through y.
int sum(int x, int y) {
  return y*(y+1)/2 - x*(x+1)/2; 
}

I cannot remember a time when a working insightful function has been worse then the naive equivalent. Even in my contrived example above the naive_sum() has inputs which would yield undefined output such as the case where y <= x while the insightful_sum() would degrade more gracefully.

In the naive style, we’d have to add conditionals to validate inputs that the maths would accept, meaning increased line count, reduced legibility, increased chance of errors, and increased nativity. The only advantage I can see to the naive style is the reduction in mathematically cluttered code.

There is a difference between performing a calculation and solving a problem. I’ve been considering the equation of a circle, . Except, you see, that’s not the entire thing. There’s a bit that we’ve dropped because it’s  zeroes (and therefore doesn’t affect our equation): . This equation contains the full information–everything that is necessary to draw and position […]