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

后端 未结 2 1872
无人及你
无人及你 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.

提交回复
热议问题