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!
Category Mathematics | Arts and crafts of Tcl-Tk programming