【问题标题】:Testing bignum arithmetic测试 bignum 算术
【发布时间】:2011-03-17 16:04:19
【问题描述】:

我正在编写一个任意精度的有理数包,我需要测试它的正确性和效率。当然,我可以自己组织一组临时测试,但由于我远不是第一个这样做的人,我认为值得一问:谁能推荐一组我可以使用的现有测试?

编辑:我最终编写了一个测试例程,每次在循环中生成三个随机数并验证各种算术恒等式是否成立。到目前为止,它在数字代码中发现了几个错误。下面是实际代码:

for (i = 0;; i++)
{
    mem = memlo;
    printf(fmtw "\r", i);

    a = rndnum();
    b = rndnum();
    c = rndnum();

    // Equality
    test(eq(a, a));
    test(!eq(a, b) || !eq(b, c) || eq(a, c));

    // Addition
    test(eq(add(add(a, b), c), add(a, add(b, c))));
    test(eq(add(a, b), add(b, a)));
    test(eq(add(a, zero), a));

    // Subtraction
    test(eq(sub(add(a, b), b), a));
    test(sub(a, a) == zero);
    test(eq(sub(a, b), add(a, sub(zero, b))));

    // Multiplication
    test(eq(mul(mul(a, b), c), mul(a, mul(b, c))));
    test(eq(mul(a, b), mul(b, a)));
    test(eq(mul(a, one), a));
    test(eq(mul(a, add(b, c)), add(mul(a, b), mul(a, c))));

    // Division
    test(b == zero || eq(div_(mul(a, b), b), a));
    test(a == zero || div_(a, a) == (one));
    test(b == zero || eq(div_(a, b), mul(a, div_(one, b))));
    test(c == zero
        || eq(div_(sub(a, b), c), sub(div_(a, c), div_(b, c))));

    // I/O
    test(eq(a, roundtrip(a)));
}

【问题讨论】:

  • 使用随机数进行测试的一件事是,如果您希望测试可重现,则需要设置种子。得到一个失败报告然后因为你不知道种子而无法重现运行真的很糟糕。

标签: testing math bignum


【解决方案1】:

尝试查看开源合理实现的单元测试。 Ruby 的rational 支持任意精度,尽管test/ruby/test_rational2.rb 中只有少数测试超过了32 位。例如:

assert_equal(Rational(2305842940494218450, 1152921470247108503),
             Rational(1073741789, 1073741827) + Rational(1073741827, 1073741789))

对于 Python 的 test_fractions.py 也是如此:

 self.assertTypedEquals(10**23, 10**22 // F(1, 10))

GNU MPL 有一些理性的单元测试,主要基于随机数。

IMath 包有一组很好的测试,例如:

qadd:-14,9/2,-20:-19/2
qadd:-60,=1,43/2:-120
qadd:375/18696391582109365451,-131/32949770573031503434,166/56750232802998421883:9906936667630486913669/616041813174061083543307811398267458734
qadd:615/80348516296708248277,=1,=2:1230/80348516296708248277

对我来说,Scheme 和 Sage 等其他开源合理的 bignum 包是如何测试的并不明显,但如果你有动力,他们的测试应该存在于某个地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多