Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
Fernando Martin Avatar asked Jul 12 '09 21:07

Fernando Martin


People also ask

How do you find the repeating part of a decimal?

Just divide the numerator by the denominator . If you end up with a remainder of 0 , then you have a terminating decimal. Otherwise, the remainders will begin to repeat after some point, and you have a repeating decimal.

How do you round a recurring decimal in Python?

To round up and down we use Python's round() function. The first argument we give that function is the number to round. The second argument the number of decimal places to round to. Python has no function that always rounds decimal digits up ( 9.232 into 9.24 ).


2 Answers

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).

like image 188
ChristopheD Avatar answered Oct 06 '22 01:10

ChristopheD


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.

like image 30
Ants Aasma Avatar answered Oct 06 '22 02:10

Ants Aasma