Re: Faster alternative to AppendTo?
- To: mathgroup at smc.vnet.net
- Subject: [mg102932] Re: Faster alternative to AppendTo?
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Wed, 2 Sep 2009 04:05:31 -0400 (EDT)
On 9/1/09 at 3:53 AM, dem_z at hotmail.com (Dem_z) 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 complete= d. 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}]; >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? It is usually significantly faster to build a nested list than flatten it. That is instead of AppendTo[orbit, k = g[k]] do orbit = {orbit {k=g[k]}} and flatten it later. But even better is to use NestWhileList That is Table[NestWhileList[g[#] &, m, # > 1 &], {m, 2, 1000000}] will generate the same list as your but faster.