PDA

View Full Version : Can anybody help me, who is good with Mathematica, with writing a sequence.


GetToTheChopa
Apr12-11, 02:09 PM
I am very new with Mathematica and I need help writing a program that generates a Farey Sequence.

Farey[n] := ??????

The result should appear as follows, for those values of N.

Farey[1] = {0/1,1/1}

Farey[2] = {0/1,1/2,1/1}

Farey[3] = {0/1,1/3,1/2,2/3,1/1}

Farey[4] = {0/1,1/4,1/3,1/2,2/3,3/4,1/1}

Farey[5] = {0/1,1/5,1/4,1/3,2/5,1/2,3/5,2/3,3/4,4/5,1/1}

Simon_Tyler
Apr13-11, 03:29 AM
This was just discussed (and is still at the top of the thread list) in very recent thread (http://www.physicsforums.com/showthread.php?t=489620) -- please look/search before you post!

By the way, are you and "INdeWATERS" (http://www.physicsforums.com/member.php?u=319108) doing the same course?

Anyway, here's another implementation for generating Farey sequences - this one implements the algorithm given in Wikipedia (http://en.wikipedia.org/wiki/Farey_sequence).
FareySequence =
Compile[{{n, _Integer}},
Module[{FS = {{0, 1}, {1, n}}, a = 0, b = 1, c = 1, d = n, f = 0},
While[c <= n, f = Quotient[n + b, d];
{a, b, c, d} = {c, d, f c - a, f d - b};
FS = Append[FS, {c, d}]];
Most@FS], CompilationTarget -> "C"];
It outputs the numerators and denominators in pairs.
For n less than a few hundred, it is comparable in speed to the solution given by DaleSpam:
Union[Flatten[Table[j/i, {i, 1, n}, {j, 0, i}]]]

To make it print fractions in all cases - including those with unit denominator, try something like
DisplayForm /@ FractionBox @@@ FareySequenceFCC[5]

(* Returns: {0/1,1/5,1/4,1/3,2/5,1/2,3/5,2/3,3/4,4/5,1/1} *)

If you have questions about how this works, look at the above linked to thread, then read the Mathematica documentation, then post here!