python 有没有办法在Python中获得分数的重复小数部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1116990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to get the repeating decimal section of a fraction in Python?
提问by Fernando Martin
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?
我正在使用 Python 的小数模块处理分数,我只想得到某个分数的重复部分。例如:如果我有 1/3,我想得到 3,如果我有 1/7,我想得到 142857。是否有任何标准函数可以做到这一点?
回答by ChristopheD
回答by user3011212
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.
我知道这个问题是很久以前的问题了,但我想人们可能还在搜索这样的东西,所以我想我会提到一些在做这件事时要记住的事情,因为我尝试编码并最终改变主意使用长除法和找出在除以余数后得到余数时发生重复的位置。实际上,我最初尝试使用 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..."
我试图获得 1/7 这样的输出,因为我的函数试图输出一个可以用作问题答案的字符串;“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
使用 Ants Aasma 提供的方法很容易找到诸如 1/7 之类的小数,但是当你尝试诸如 1/35 之类的东西时会很痛苦——这不能被分成一个充满 9 的数字。首先,任何分母都必须将任何 10 的因数除以 - 即除掉所有的 5 和 2,将诸如 1/35 之类的分数转换为 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.
对于像 1/70 这样的分数,我认为最好的方法是实际找到 1/7,然后在小数点后加上 0。对于 1/35,您可以将其转换为 0.2/7,然后再转换为 2/7,在重复部分和小数位之间有一个 0。
Just a couple of tips to keep in mind if using Ants Aasma's suggested method.
如果使用 Ants Aasma 的建议方法,请记住一些提示。
回答by Ants Aasma
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.
找到 10**k - 1 形式的第一个数字,它可以被分数的分母整除,再除以分母,再乘以分子,你就得到了重复部分。