Calculating Mathematical Constants

I’ve been learning Calculus recently which has revitalized my interest in Mathematics. I found myself looking for a challenge, and so I decided to write some simple functions which will calculate popular mathematical constants. So far, I’ve written functions for calculating pi, e, and phi (golden ratio). There are various methods for calculating these constants using series or limits. However, I’m working with 80-bit precision, so I had to choose an ideal formula to obtain the max precision. Basically, numbers can’t be allowed to become too large or too small.

After an initial implementation, I worked on improving the code, which included increasing precision, optimizing, or simplifying the code. Because all of these constants are infinite sequences, you can only calculate to a specific precision, which I defined as number of rounds.

All examples are written on D and posted on DPaste so that you can see the actual results (or fork and play with the code yourself).

                                                                         

First up is pi: http://dpaste.dzfl.pl/ac33a0790

Image

The only optimization I could devise is replacing (-1)^n with a conditional.

                                                                         

Second is e: http://dpaste.dzfl.pl/b5604425

Image

This is a rather simple formula which I was surprised by how much it can be simplified in code. The first problem to tackle was the factorial. Even a small k could result in a very large number which is a problem for precision. Instead, (1/k!) is expanded to (1/1)(1/2)(1/3)(1/4) … which could be further optimized by remembering the product of the previous iteration. This resulted in (product *= 1/k), which could be further simplified to (product /= k).

                                                                         

Finally is phi (golden ratio): http://dpaste.dzfl.pl/5b8af89c

Image or Image

This series was more challenging to simplify, but mostly thanks to CAS (computer algebra systems), I discovered that the polynomials could be simplified by factoring. But after implementing it as a series, I discovered that the golden ratio has the very simple formula, (1 + sqrt(5))/2.

Advertisements