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

无人久伴 提交于 2019-11-28 23:33:52

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!