According to Wikipedia, A fraction is terminating if it can be represented in the form of k/(2^n * 5^m)
, where k, n, and m are integers.
#assumes that the fraction is already fully reduced
#e.g. numerator and denominator are coprime
function isTerminating(numerator, denominator):
while denominator % 2 == 0:
denominator /= 2
while denominator % 5 == 0:
denominator /= 5
return denominator == 1
If you have the fraction in an IEEE float, then it always terminates, as long as it is not NaN or +/- infinity. Finite numbers in floats are represented as c * b^q
. The terms may be rearranged to be c / (b^-q)
. b is always 2 or 10, so the number fits the k/(2^n * 5^m)
format and is therefore a terminating fraction.