Version 5 of Periodic decimal fractions

Updated 2002-04-29 20:49:55

Richard Suchenwirth 2002-04-27 - Periodic decimal fractions are numbers where a sequence of digits behind the decimal point (the period) is endlessly repeated, for example:

 1/7 = 0.142857142857..
 1/3 = 0.3333..

The following routine tries to detect a period in a given number and returns the period (might be 0 for integers or non-strict periods like

 1/2 = 0.5000..

or (implicitly) an empty string if no period could be detected - then the input number might be irrational (not representable by a nominator/divisor expression, e.g. sqrt(2)), or it has a period longer than 7 digits, which can not be confirmed at the maximum tcl_precision of 17, a limit imposed by the underlying double representation in C. For instance, 1/17 is certainly periodic, but the period is out of sight for Tcl's expr math..


 proc period x {
        set frac [expr {abs(double($x)-int($x))}]
        if {!$frac || [string length $frac]<10} {return 0}
        set digits [string range $frac 2 end]
        foreach n {1 2 3 4 5 6 7} {
            foreach offset {0 1 2 3 4 5 6} {
                    set try [string range $digits $offset [expr $offset+$n-1]]
                if {[regexp .{0,$n}$try\($try)+.{0,$n}$ $digits]} {
                        return $try
                }
            }
        }
 }

Arjen Markus As the fraction is contained in a string, there ought to be no problem with very long periods:

   set long_fraction "0.123456789012345678901234567890"

As long, of course, as you avoid interpreting the string as a number! RS admits that he does, by letting expr compute the fractional part...


KBK In the spirit of Fraction math, let's do the period of a rational number whose numerator and denominator are integers. The following has no trouble finding out that 1/17 repeats with a period of 16 places.

 proc period2 { n d } {
     set x 0
     while { 1 } {
         set r [expr { $n % $d }]
         if { $r == 0 } {
             return 0
         } elseif { [info exists seen($n)] } {
             return [expr { $x - $seen($n) }]
         } else {
             set seen($n) $x
             incr x
             set n [expr { 10 * $r }]
         }
     }
 }
 for { set i 1 } { $i <= 20 } { incr i } {
     puts [list $i [period2 1 $i]]
 }

There is some interesting number theory here, but I haven't the time to get into it; I've typed this in in about 15 minutes while waiting for a test to run.


Category Mathematics | Arts and crafts of Tcl-Tk programming