0

Possible Duplicate:
How to know the repeating decimal in a fraction?

Is there a way to tell if a decimal is terminating or repeating?

Example: I have fraction: 1/3 and it's repeating decimal - 0.33333333333333333333 I have fraction 1/2 and it's terminating decimal - 0.5

I don't have any idea how i can do it.

Community
  • 1
  • 1
Yozer
  • 648
  • 1
  • 11
  • 26
  • Related: http://stackoverflow.com/questions/8946310/how-to-know-the-repeating-decimal-in-a-fraction – Oded Jan 23 '13 at 13:38
  • what do you mean by "repeating" ? irrational numbers ? any number that can't be acuratly represented by a float ? by a double ? – Oren Jan 23 '13 at 13:39
  • Thanks, i search on stackoverflow, but i didn't see that. – Yozer Jan 23 '13 at 13:40
  • When you say " I have fraction: 1/3", in what form do you 'have' it? As the pair of integers `1` and `3`, or something else? – AakashM Jan 23 '13 at 13:41
  • There is no built in way to do this but if you are willing to put in some effort you might be able to follow @MichaelAnderson's guide in this post: http://stackoverflow.com/questions/12098461/how-can-i-detect-if-a-float-has-a-repeating-decimal-expansion-in-c – Moriya Jan 23 '13 at 13:42

1 Answers1

7

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.

Kevin
  • 74,910
  • 12
  • 133
  • 166