← Back to context

Comment by avian

4 years ago

> #define M_PI 3.2f

A long time ago, a friend who was studying mathematics at the time, approached me laughing hysterically and showed me a page in an "intro to C"-style book. It showed an example of how one would write a "get circumference of a circle" function. At the top of the code, there was a #define for the value of pi.

The text describing the code said something like this about why pi is #defined and not included directly in the expression:

"We define pi as a constant for two reasons: 1) it makes the expressions using it more readable 2) should the value of pi ever change, we will only have to change it in one place in the code"

As funny as it sounds, there is still a bit of truth in there, though: code might change from using floats to double for example, so you might want to replace single-precision constants by double-precision constants. Only need to replace a single pi constant in that case. :)

There is a similar joke in the book Learning Perl, 3rd Edition by Randal L. Schwartz and Tom Phoenix. I wrote a post about it here fourteen years ago: https://susam.net/blog/from-perl-to-pi.html . Quoting from the book:

"It's easier to type $pi than 𝜋, especially if you don't have Unicode. And it will be easy to maintain the program in case the value of ever changes."

There is also a comment by Randal Schwartz in the comments section where he credits Tom Phoenix with that particular bit of humour.

  • Good catch! I might be misremembering this event and it was actually Perl, not C. I see Learning Perl, 3rd Edition was published in 2001, which does put its publication at about the right time in early 00s.

But why is it then 3.2f instead of 3.1? Seeing as 3.14 gets rounded to 3.1. Or is that part of the joke and the reason for why the value nee changing?

  • Regardless of the actual answer, it can make sense to round it up depending on the use case e.g. if you’re calculating the tolerances for a shaft onto which you place a disk, computing the disk diameter (and thus volume, and weight) to be larger than actual provides a safety margin which rounding down would not. Any additional safety margin added afterwards might not be sufficient in all round-down cases.

  • Sorry, I should be more clear. This is a line from the header linked by the parent comment that reminded me of this story.