MathGroup Archive 2009

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

Search the Archive

Re: Faster alternative to AppendTo?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg102942] Re: [mg102886] Faster alternative to AppendTo?
  • From: "Kurt" <ekt at fastmail.net>
  • Date: Wed, 2 Sep 2009 04:07:18 -0400 (EDT)
  • References: <200909010753.DAA18801@smc.vnet.net>
  • Reply-to: ekt at fastmail.net

Try this (you're on your own for timing long runs)

collatz[x_Integer/;EvenQ[x]]:=x/2
collatz[x_Integer]:=3 x +1

Then the orbit of an integer n is given by

FixedPointList[collatz,n]

If you'd like to be cautious and put a limit on the calculation, you may
with

FixedPointList[collatz, n, limit]

Of course you can restart the investigation by using the last entry in
the list for n as n in a new calculation.

Kurt


On Tue, 01 Sep 2009 03:53 -0400, "Dem_z" <dem_z 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.
> 
-- 
  Love,
  Kurt
  ekt at fastmail.net



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