查找将浮点数列表转换为整数列表的公因数 [英] Find common factor to convert list of floats to list of integers

查看:82
本文介绍了查找将浮点数列表转换为整数列表的公因数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自其他函数的浮点列表. 我知道在理想世界中存在一个共同的因素 可用于将每个项相乘以获得整数列表. 可能会有一些小的数字噪声(〜1e-14).

I have a list of floats which comes from some other function. What I know is that in ideal world there exist a common factor which can be used to multiply each term to obtain list of integers. There could be some small numerical noise (~1e-14).

例如

[2.3333333333333335, 4.666666666666667, 1.0, 1.6666666666666667]

这里每一项可以乘以3以获得

here each term can by multiplied by 3 to obtain

[7.0, 14.0, 3.0, 5.0]

我如何找到这个名词?我们可以假设存在整数解.

How can I find this term? We can assume integer solution exists.

任何有帮助的评论将不胜感激

Any helpful comments will be appreciated

推荐答案

Python的 Fraction 类型可以将分母小于1000000的浮点数转换为有理数,然后可以找到最低的公分母.

Python's Fraction type can convert floating points to rationals with denominators under 1000000, and then you can find the lowest common denominator.

>>> from fractions import Fraction
>>> a = [2.3333333333333335, 4.666666666666667, 1.0, 1.6666666666666667]
>>> [Fraction(x).limit_denominator() for x in a]
[Fraction(7, 3), Fraction(14, 3), Fraction(1, 1), Fraction(5, 3)]

使用数学来找到最小公倍数的一种直接方法. gcd 函数:

>>> denoms = [3,3,1,2]
>>> functools.reduce(lambda a,b: a*b//math.gcd(a,b), denoms)
6

这篇关于查找将浮点数列表转换为整数列表的公因数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆