Question

I've always been curious: how can I perform arithmetic operations on very long decimals--for example, calculating pi to the 3000th decimal place (especially in an imperative language)?

Was it helpful?

Solution

Use a language or library that supports arbitrary precision numbers...?

In Python, ints will auto-promote to longs which are arbitrary size. You could use a second value for keeping track of how many decimals to shift over by to get a sort of arbitrary precision floating point.

In Java you could use the BigDecimal class, which represents "Immutable, arbitrary-precision signed decimal numbers".

I'm sure other examples exist in other languages.

OTHER TIPS

For languages that don't support computations on bignums, there are often libraries. You might have a look at GMP, for example. The docs will give you pointers to some of the typical algorithmic approaches.

Making bignum arithmetic fast is difficult, so there are some pretty convoluted algorithms out there...

You either have to work with the data at the digit level (e.g. calculate each digit incrementally or deterministically) or define new data structures that have a sufficient number of bits to provide adequate precision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top