views:

250

answers:

4

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)?

A: 

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.

ParoXoN
+3  A: 

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.

Laurence Gonsalves
+3  A: 

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...

simon
+1  A: 

You may find some useful answers in this prior question: http://stackoverflow.com/questions/25375?sort=newest

bdonlan

related questions