有没有办法在Python中获取分数的重复小数部分?

发布于 2024-07-26 07:23:03 字数 102 浏览 3 评论 0 原文

我正在使用 Python 的小数模块处理分数,我想只得到某个分数的重复部分。 例如:如果我有 1/3,我想得到 3,如果我有 1/7,我想得到 142857。有没有标准函数可以做到这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情话难免假 2024-08-02 07:23:03

由于给出答案可能会破坏 euler 项目(在 stackoverflow 上通常不会这样做),所以我想给出这个提示:阅读 这个(第 1.2 节应该引起注意)。

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

薄荷梦 2024-08-02 07:23:03

我知道这个问题是很久以前的事了,但我认为人们可能仍在搜索类似的东西,所以我想我会提到一些在做这件事时要记住的事情,因为我尝试编码并最终改变了我的想法使用长除法和当除以余数后,找出重复发生的位置。 我其实最初是尝试使用Ants Aasma建议的方法。

我试图在 1/7 中获得这样的输出,因为我的函数试图输出一个可以用作问题答案的字符串;
“0.142857 142857...”

使用 Ants Aasma 提供的方法很容易找到诸如 1/7 之类的小数,但是当您尝试诸如 1/35 之类的数字时,它会变得很痛苦 - 这不能被划分为充满 9 的数字。 首先,任何分母都必须除以 10 的任何因数 - 即除掉所有 5 和 2,将分数(例如 1/35)转换为 0.2/7

对于分数(例如 1/70),我相信最好的方法是实际找到 1/7,然后在小数点后面贴上 0。 对于 1/35,您可以将其转换为 0.2/7,然后转换为 2/7,并在重复部分和小数位之间添加 0。

如果使用 Ants Aasma 的建议方法,请记住一些提示。

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.

靑春怀旧 2024-08-02 07:23:03

找到 10**k - 1 形式的第一个数字,该数字恰好除以分数的分母,将其除以分母,然后乘以分子,即可得到重复部分。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文