Mathematica Can anybody help me, who is good with Mathematica, with writing a sequence.

AI Thread Summary
The discussion centers on generating a Farey Sequence in Mathematica, with a user seeking assistance in writing a program for this purpose. The expected output for various values of N is provided, showcasing the sequence's structure. One participant shares a compiled implementation of the Farey sequence algorithm, which efficiently generates the sequence using a while loop and outputs numerators and denominators in pairs. Another method is mentioned, which utilizes a union of fractions generated through a table. To ensure proper display of fractions, a suggestion is made to use DisplayForm with FractionBox. Participants are encouraged to refer to previous discussions and Mathematica documentation for further clarification and understanding.
GetToTheChopa
Messages
2
Reaction score
0
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}
 
Physics news on Phys.org
This was just discussed (and is still at the top of the thread list) in https://www.physicsforums.com/showthread.php?t=489620" -- please look/search before you post!

By the way, are you and https://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 http://en.wikipedia.org/wiki/Farey_sequence" .
Code:
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:
Code:
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
Code:
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!
 
Last edited by a moderator:

Similar threads

Replies
8
Views
4K
Replies
5
Views
3K
Replies
17
Views
1K
Replies
1
Views
4K
Replies
2
Views
3K
Replies
1
Views
3K
Replies
17
Views
970
Back
Top