How can I make a “working” repeating decimal representation of a rational number?

后端 未结 2 1858
无人及你
无人及你 2020-12-15 09:35

I\'ve figured out how to display the repeating part of a repeating decimal using OverBar.

repeatingDecimal doesn\'t actually work as a repeating decimal

相关标签:
2条回答
  • 2020-12-15 09:59

    You shouldn't have given your repeatingDecimal DownVaues, but rather, FormatValues:

    ClearAll[repeatingDecimal];
    Format[repeatingDecimal[q2_]] := 
    Module[{a}, 
     a[{{nr__Integer}, pt_}] := 
     StringJoin[
      Map[ToString, 
       If[pt > -1, Insert[{nr}, ".", pt + 1], 
      Join[{"."}, Table["0", {Abs[pt]}], {nr}]]]];
      (*repeating only*)
     a[{{{r__Integer}}, pt_}] := 
     Row[{".", OverBar@StringJoin[Map[ToString, {r}]]}];
    (*One or more non-repeating;
    more than one repeating digit KEEP IN THIS ORDER!!*)
    a[{{nr__, {r__}}, pt_}] := 
     Row[{StringJoin[
       Map[ToString, 
        If[pt > -1, Insert[{nr}, ".", pt + 1], 
         Join[{"."}, Table["0", {Abs[pt]}], {nr}]]]], 
      OverBar@StringJoin[Map[ToString, {r}]]}];
    (*One or more non-repeating;one repeating digit*)
    a[{{nr__, r_Integer}, pt_}] := 
      Row[{StringJoin[Map[ToString, {nr}]], ".", 
       OverBar@StringJoin[Map[ToString, r]]}];
    a[RealDigits[q2]]]
    

    Then, you can give it also UpValues, to integrate with common functions, for example:

    repeatingDecimal /: Plus[left___, repeatingDecimal[q_], right___] := left + q + right;
    repeatingDecimal /: Times[left___, repeatingDecimal[q_], right___] :=  left * q * right;
    

    Then, for example,

    In[146]:= repeatingDecimal[7/31]+24/31
    
    Out[146]= 1
    

    You can extend this approach to other common functions which you may want to work with repeatingDecimal.

    0 讨论(0)
  • 2020-12-15 10:00

    Here is a possible refactoring of your updated code. I think it works this time (fingers crossed). If you do not need the color highlighting, you can leave off ~Style~ and the rest of that line.

    ClearAll[repeatingDecimal];
    
    Format[repeatingDecimal[n_Integer | n_Real]] := n;
    
    Format[repeatingDecimal[q_Rational]] :=
     Row[{IntegerPart@q, ".", RealDigits@FractionalPart@q}] /.
      {{ nr___Integer, r_List:{} }, pt_} :>
       Row@Join[
          "0" ~Table~ {-pt},
          {nr},
          If[r === {}, {}, {OverBar@Row@r}]
          ] ~Style~ If[r === {}, Blue, If[{nr} === {}, Red, Gray]]
    
    repeatingDecimal /:
      (h : Plus | Times)[left___, repeatingDecimal[q_], right___] :=
        h[left, q, right];
    

    I will leave this older version here for reference, but I am now making edits to the Question community wiki.

    0 讨论(0)
提交回复
热议问题