MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Faster alternative to AppendTo?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg102908] Re: Faster alternative to AppendTo?
  • From: Emu <samuel.thomas.blake at gmail.com>
  • Date: Wed, 2 Sep 2009 04:01:12 -0400 (EDT)
  • References: <h7ijtl$ibb$1@smc.vnet.net>

On Sep 1, 5:53 pm, Dem_z <de... at hotmail.com> wrote:
> Hey, sorry I'm really new. I only started using mathematica recently, so I'm not that savvy.
>
> Anyways, I wrote some code to calculate (and store) the orbits around numbers in the Collatz conjecture.
>
> "Take any whole number n greater than 0. If n is even, we halve it (n/2), else we do "triple plus one" and get 3n+1. The conjecture is that for all numbers this process converges to 1. "
>  http://en.wikipedia.org/wiki/Collatz_conjecture
>
> (*If there's no remainder, divides by 2, else multiply by 3 add 1*)
> g[n_] := If[Mod[n, 2] == 0, n/2, 3 n + 1]
>
> (*creates an empty list a. Loops and appends the k's orbit into variable "orbit", which then appends to variable "a" after the While loop is completed.  New m, sets new k, which restarts the While loop again.*)
> a = {};
> Do[
>   k = m;
>   orbit = {k};
>   While[k > 1, AppendTo[orbit, k = g[k]]];
>   AppendTo[a, orbit];
>   , {m, 2,1000000}];
>
> Anyways it seems that the AppendTo function gets exponentially slower, as you throw more data into it. Is there a way to make this more efficient? To calculate a million points takes days with this method.

Always try to avoid using Append and AppendTo. Here's one way

In[186]:= Table[NestWhileList[If[EvenQ[#],#/2,3 #+1]&,m,#=!=1&],{m,
2,10}]
Out[186]= {{2,1},{3,10,5,16,8,4,2,1},{4,2,1},{5,16,8,4,2,1},
{6,3,10,5,16,8,4,2,1},{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1},
{8,4,2,1},{9,28,14,7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1},
{10,5,16,8,4,2,1}}

You can see that it's fairly fast.

In[187]:= Table[Table[NestWhileList[If[EvenQ[#],#/2,3 #+1]&,m,#=!=1&],
{m,2,upper}]//Timing//First,{upper,1000,10000,1000}]
Out[187]=
{0.231005,0.514937,0.826265,1.1636,1.48742,1.85433,2.1733,2.5272,2.8803,3.27888}

Sam


  • Prev by Date: Re: Nesting functional commands
  • Next by Date: Re: Faster alternative to AppendTo?
  • Previous by thread: Re: Faster alternative to AppendTo?
  • Next by thread: Re: Faster alternative to AppendTo?