Mimsy Were the Borogoves

Hacks: Articles about programming in Python, Perl, PHP, and whatever else I happen to feel like hacking at.

Adding functions to padmath

Jerry Stratton, August 23, 2012

The simple padmath replacement for MathPad works for almost everything I used MathPad for. Every once in a while, however, I need a function that bc doesn’t have but that MathPad did. Three of the most common things I end up needing are π for determining area, and abs and trunc for getting the absolute value or to drop the fractions from a value.

The bc program does support creating functions, so I’ve added those three items to the prepended text that, previously, just set the system to use four decimal points.

Replace “print WRITE "scale=4\n";” with:

[toggle code]

  • #functions
  • print WRITE <<'ENDFUNCTIONS';
  • #padmath values
  • pi = 3.1416
  • #padmath functions
  • define abs(value) {
    • if (value < 0) {
      • return -value
    • } else {
      • return value
    • }
  • }
  • define trunc(value) {
    • old_scale=scale
    • scale=0
    • int_value=value/1
    • scale=old_scale
    • return int_value
  • }
  • #not in MathPad
  • define ceiling(value) {
    • return -floor(-value);
  • }
  • define floor(value) {
    • int_value = trunc(value)
    • if (value != int_value && value < 0) {
      • int_value = int_value -1
    • }
    • return int_value
  • }
  • scale=4
  • ENDFUNCTIONS

So I can now do something like this because I’m looking for a year:

  • --25-year shingles reduced 25% for being overlay, and then they’re already five years old
  • 25*.75-5: 13.75
  • 2012+trunc(#): 2025

Or, calculate the area of a circle:

  • diameter = 9
  • radius = diameter/2
  • pi*radius^2: 63.6174

Doing this I also got carried away and added ceiling and floor to the mix, because just using trunc isn’t always exactly right. Using either of those extra functions will make the pad incompatible with MathPad, however.

In response to A simple math pad in Perl: I finally upgraded to Lion at the office; that means no more Mark Widholm MathPad. I got a simple replacement working using SilverService and Perl.

  1. <- Yet Another Pad Calculator
  2. MathPad is back! ->