Fernando Martin
Fernando Martin

Reputation: 522

Is there any way to get the repeating decimal section of a fraction in Python?

I'm working with fractions using Python's decimal module and I'd like to get just the repeating part of a certain fraction. For example: if I had 1/3 I'd like to get 3, if I had 1/7 I'd like to get 142857. Is there any standard function to do this?

Upvotes: 11

Views: 21778

Answers (3)

user3011212
user3011212

Reputation: 41

I know this question was a long time ago, but I figured people probably still search something like this so I figured I'd mention some things to keep in mind when doing it since I tried coding and eventually changed my mind to using long division and finding where repetition occurs when you get a remainder after dividing into it. I was actually originally trying to use the method suggested by Ants Aasma.

I was trying to get output such as this for 1/7, since my function was trying to output a string which could be used as an answer to a question; "0.142857 142857..."

Decimals such as 1/7 are very easily found using the method provided by Ants Aasma, however it gets painful when you try something such as 1/35 - this cant be divided into a number full of 9s. First of all, any denominators will have to have any factors of 10 divided out - i.e. divide out all the 5s and 2s, converting a fraction such as 1/35 to 0.2/7

For a fraction such as 1/70, I believe the best way is to actually find 1/7 and then stick a 0 right after the decimal place. For 1/35, you would convert it to 0.2/7 and then to 2/7 with a 0 between the repeating part and the decimal place.

Just a couple of tips to keep in mind if using Ants Aasma's suggested method.

Upvotes: 3

ChristopheD
ChristopheD

Reputation: 116287

Since giving the answer could be a spoiler for project euler (which is generally not done here at stackoverflow), I'd like to give this hint: read this (section 1.2 should ring a bell).

Upvotes: 17

Ants Aasma
Ants Aasma

Reputation: 54935

Find the first number of the form 10**k - 1 that divides exactly by the denominator of the fraction, divide it by the denominator and multiply by the numerator and you get your repeating part.

Upvotes: 2

Related Questions