Re: Faster alternative to AppendTo?
- To: mathgroup at smc.vnet.net
- Subject: [mg102911] Re: [mg102886] Faster alternative to AppendTo?
- From: Murray Eisenberg <murray at math.umass.edu>
- Date: Wed, 2 Sep 2009 04:01:45 -0400 (EDT)
- Organization: Mathematics & Statistics, Univ. of Mass./Amherst
- References: <200909010753.DAA18801@smc.vnet.net>
- Reply-to: murray at math.umass.edu
There's a package Collatz.m that's long been distributed with Mathematica. For Mathematica 7, it's in: $InstallationDirectory\Documentation\English\System\ExampleData You can copy the definitions from that .m file and try it directly without having to load the package: Collatz[1] := {1} Collatz[n_Integer]:= Prepend[Collatz[3 n + 1], n] /; OddQ[n] && n > 0 Collatz[n_Integer] := Prepend[Collatz[n/2], n] /; EvenQ[n] && n > 0 Collatz[1000000];//Timing {1.0842*10^-19, Null} (* on my PC *) 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 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. > -- Murray Eisenberg murray at math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305
- References:
- Faster alternative to AppendTo?
- From: Dem_z <dem_z@hotmail.com>
- Faster alternative to AppendTo?