【问题标题】:Find regular intervals in a set of unordered numbers在一组无序数中查找规则区间
【发布时间】:2014-07-19 09:27:24
【问题描述】:

我有一组从文件中读取的非唯一实数。

所有这些数字都是从一个线性空间产生的,也就是说,数字之间的差异总是一个固定值的倍数,可以说是线性空间的“步长”或“网格大小”。

每个现有值通常会在文件中出现多次。

我的目标是找出这些值的间距,以便我可以将每个(唯一)值放入一个数组中并使用索引访问它的值。

【问题讨论】:

  • 请输入输出样例

标签: arrays sorting math language-agnostic indexing


【解决方案1】:

您正在寻找这些数字的最大公约数。这是在 Python 中的:

def gcd( a, b ):
    "greatest common divisor"
    while True:
        c = a % b
        if c < 1e-5:
            return b
        a, b = b, c

def gcdset( a_set ):
    "use the pairwise gcd to find gcd of a set"
    x = a_set.pop()
    total = x
    for u in a_set:
        x = gcd( u, x )
        # the following step is optional,
        # some sort of stabilization just for improved accuracy
        total = total + u
        x = total / round(total/x)

    return x

# the list where we want to find the gcd
inputlist = [2239.864226650253, 1250.4096410911607, 1590.1948696485413,
    810.0479848807954, 2177.343744595695, 54.3656365691809, 2033.2748076873656,
    2074.049035114251, 108.7312731383618, 2188.216871909531]

# we turn it into a set to get rid of duplicates
aset = set(inputlist)
print(gcdset( aset ))

如果你身边没有 Python,你可以在这里玩这个代码:http://ideone.com/N9xDWA

【讨论】:

  • 顺便提一下,Python 是我首选的编程语言。我会测试你的答案并迅速给出一些反馈,但这似乎正是我所需要的。现在谢谢。
  • @heltonbiker 对于许多数字,gcd 可能会变得不稳定。我添加了一些代码来稳定它。现在它应该提供完美的准确性。
  • 太棒了,明天这肯定会被测试。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多