[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: shell wrappers for trig and other mathematical functions



On Tue, Oct 01, 2019 at 08:32:01PM -0700, Dan Hitt wrote:
> I'm half-way looking for some shell wrappers for common trig functions like
> sin, cos, exp, log, and others.
> 
> I'm aware of bc, but it seems cumbersome.

The shell way would be to do it with bc (or dc, if you want it
cryptic).

Note that the shell itself doesn't have a notion of floating
point numbers: you're passing them around as strings, so
you'd want to "spend as much time as possible" at the one
or the other "side", and "cross the border" at rather few
and defined times.

Here's how I display my battery status as a shell script
using bc:

  BAT='/sys/class/power_supply/BAT0'
  AC='/sys/class/power_supply/AC'
  FULL=$(cat $BAT/energy_full)
  NOW=$(cat $BAT/energy_now)
  case $(cat $AC/online) in
    0) online="BAT" ;;
    1) online="AC " ;;
    *) online="???" ;;
  esac
  echo -ne "$online " ; dc -e "5k $NOW $FULL / p" ; date +"%F%a%n  %T"

Now there are many holes in that: this assumes, f.ex. that /sys/class/...
all produce sensible results (no spaces in them). But that's how I let
bc cope with the "floating point" part -- the shell does the plumbing
the way it likes to plumb: variable substitution, etc.

I think this is the way shell is designed. You're trying to bend it
into a different shape, which I'm sure is possible -- but I doubt
it'll make you happy (it's on you to try, though, and don't let
others discourage you!).

Think a moment about "sin(1) + cos(1)" (and that the shell's "+"
is going to bark at this [1]) to consider that you're looking into
implementing a whole arithmetic interpreter... and then you're
already at dc, take or give.

Cheers

[1] try "echo $((0.6 + 1.3))" in your bash to see what I mean :)

-- t

Attachment: signature.asc
Description: Digital signature


Reply to: