[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Computation time for newcommer
From: |
Jordi Gutiérrez Hermoso |
Subject: |
Re: Computation time for newcommer |
Date: |
Tue, 25 Sep 2012 09:19:22 -0400 |
On 25 September 2012 07:46, Joza <address@hidden> wrote:
> So I'm trying to compute the value of pi using a series with a billion terms
> (n):
>
> for i=1:1:n
>
> x(i) = ( (-1)^(i + 1) ) / ( (2*i) - 1 );
>
> end
>
> % Sum all the values in the vector x
>
> value = 4*sum(x)
Oh, boy, let's see...
Octave is an array-based language, and loops are slow. While this may
improve with the next major release, for the moment you need to read
and absorb this:
http://www.gnu.org/software/octave/doc/interpreter/Vectorization-and-Faster-Code-Execution.html
Instead of this loop, you should write
i = 1:1e9;
x = -1.^(i+1)./(2*i - 1);
However, storing one billion doubles is a bit silly. Each double is 8
bytes, so you're storing 8e9 bytes or about 7.6 gigabytes. You only
have 4 gigabytes of RAM, so you cannot store this vector in memory. If
you try, your computer may get into a thrash as it starts swapping
virtual memory:
http://en.wikipedia.org/wiki/Thrashing_%28computer_science%29
As you probably know, you have chosen one of the worst possible
methods for computing digits of pi. This series converges extremely
slowly. If you really want to use this method, you should at least use
a series acceleration method such as Richardson extrapolation:
http://en.wikipedia.org/wiki/Richardson_extrapolation
Although it doesn't apply to your problem specifically, since the
error term of an alternating series is easily seen to be bound by the
nth term and a billion terms will only give you about 9 digits of
precision, you should know that Octave is not a CAS (computer algebra
system) and the hardware floats that it's using only have about 16
decimal digits of precision, or 52 binary digits (bits) plus one
implicit bit, to be precise. Please consult this:
http://wiki.octave.org/FAQ#Why_is_this_floating_point_computation_wrong.3F
If you plan to compute digits of pi, a program better suited for it
than Octave would be Sage with the number theory routines it has
inherited from Pari/GP:
http://sagemath.org/
HTH,
- Jordi G. H.