Article 5CE2H Bootstrapping a minimal math library

Bootstrapping a minimal math library

by
John
from John D. Cook on (#5CE2H)

Sometimes you don't have all the math functions available that you would like. For example, maybe you have a way to calculate natural logs but you would like to calculate a log base 10.

The Unix utility bc is a prime example of this. It only includes six common math functions:

  • sine
  • cosine
  • arctangent
  • natural log
  • exp
  • square root

Users are expected to know how to calculate anything else they need from there. (Inexplicably, bc also includes a way to calculate Bessel functions.)

This post collects formulas that let you bootstrap the functions listed above into all the trig and hyperbolic functions and their inverses.

Logarithms

Most programming languages provide a way to compute natural logs but not logs in bases other than e. If you have a way to compute logs in base b, you can compute logs in any other base via

bootstrap_log.svg

So, for example, you could compute the log base 10 of a number by computing its natural log and dividing by the natural log of 10.

Exponents

If you have a way to calculate ex and natural logs, you can compute xy via

bootstrap_exponent.svg

Since square roots correspond to exponent 1/2, you can use this to compute square roots.

Trig functions

If you have a way to calculate sine and cosine, you can calculate the rest of the six standard trig functions.

bootstrap_trig.svg

Inverse trig functions

If you have a way to calculate inverse tangent, you can bootstrap it to compute the rest of the inverse trig functions.

bootstrap_arctan.svg

Also, you can use arctan to compute since = 4 arctan(1).

Hyperbolic functions

If you have a way to compute exponentials, you can calculate hyperbolic functions.

bootstrap_hyperbolic.svg

Inverse hyperbolic functions

If you can compute square roots and logs, you can compute inverse hyperbolic functions.

bootstrap_inverse_hyperbolic.svg

Complex branch cuts

Up to this point this post has implicitly assumed we're only working with real numbers. When working over complex numbers, inverse functions get more complicated. You have to be explicit about which branch you're taking when you invert a function that isn't one-to-one.

Common Lisp worked though all this very thoroughly, defining arc tangent first, then defining everything else in a carefully chosen sequence. See Branch cuts and Common Lisp.

The post Bootstrapping a minimal math library first appeared on John D. Cook.s2eAgfWE4TQ
External Content
Source RSS or Atom Feed
Feed Location http://feeds.feedburner.com/TheEndeavour?format=xml
Feed Title John D. Cook
Feed Link https://www.johndcook.com/blog
Reply 0 comments