Computing pi with bc

I wanted to stress test the bc calculator a little and so I calculated π to 10,000 digits a couple different ways.

First I ran time bc -l <<< “scale=10000;4*a(1)” which calculates π as 4 arctan(1).

This took 2 minutes and 38 seconds.

I imagine bc is using some sort of power series to compute arctan, and so smaller arguments should converge faster.

So next I used a formula due to John Machin (1680–1752).

time bc -l <<< “scale=10000;16*a(1/5) – 4*a(1/239)” This took 52 seconds.

Both results were correct to 9,998 decimal places.

When you set the scale variable to n, bc doesn’t just carry calculations out to n decimal places; it uses more and tries to deliver n correct decimal places in the final result.

Why bc This quirky little calculator is growing on me.

For one thing, it launches instantly.

It doesn’t give you a command prompt, and so if you launch it in quiet mode you could think that it’s still loading when in fact it’s waiting on you.

And if you send bc code with a here-string as in the examples above, you don’t even have to launch it per se.

If you want to try bc, I’d recommend launching it with the options -lq.

You might even want to alias bc to bc -lq.

The -l option loads math libraries.

You’d think that would be the default for a calculator, but bc was written in a more resource-constrained time when you didn’t load much by default.

The -l option also sets scale to 20, i.

e.

you get twenty decimal places of precision; the default is zero!.The -q option isn’t necessary, but it starts bc in quiet mode, suppressing three lines of copyright and warranty announcements.

As part of its minimalist design, bc only includes a few math functions, and you have to bootstrap the rest.

For example, it includes sine and cosine but not tangent.

More on how to use the built-in functions to compute more functions here.

.

. More details

Leave a Reply