linspace c ++ vs matlab浮点预测

时间:2017-06-29 08:23:18

标签: c++ matlab

我试图在c ++中实现Linspace 我创建了一些随机测试并且存在精度问题,我不明白为什么。

c ++实现

std::vector<double> libcalc::linear_space(double a, double b, unsigned int n)
{
    std::vector<double> array(n,a);
    //return an empty array if number of spaces is 0
    //return a if number of spaces is 1
    if (n <= 1 || fabs(a - b) < std::numeric_limits<double>::epsilon())
    {
        return array;
    }

    //we want to be sure we get exactly b in the end
    for (unsigned int i = 0; i < n-1; ++i)
    {
        array[i] = a + ((b - a)*i)/(n-1);
    }
    array[n - 1] = b;
    return array;
}

捕获单元测试框架工作测试

auto reverse = [](std::vector<double> const& x)
{
    std::vector<double> output(x.size());
    std::reverse_copy(x.begin(), x.end(), output.begin());

    return output;
};

SCENARIO("Any linear space (a, b) with two or more points will be same as"
    " the reversed linear space of (b, a)")
{
    GIVEN("a range of points to check starting from 2")
    {
        unsigned int starting_point = 2;
        unsigned int ending_point = 10;

        THEN("the linear space (a, b) is same as reversed linear space (b, a)")
        {
            for (unsigned int n = starting_point; n < ending_point; ++n)
            {
                auto a = any_value();
                auto b = any_value();

                auto x = linear_space(a, b, n);
                auto y = reverse(linear_space(b, a, n));
                INFO("a: " << a);
                INFO("b: " << b);
                INFO("n: " << n);
                REQUIRE(x.size() == y.size());
                CHECK(x == y);
            }
        }
    }
}

c ++代码结果是

  CHECK( x == y )
with expansion:
  { -296336583.43100381, 273999144.43620467, 844334872.30341315, 1414670600.
  1706216, 1985006328.0378299 }
  ==
  { -296336583.43100381, 273999144.43620443, 844334872.30341291, 1414670600.
  1706214, 1985006328.0378299 }
with messages:
  a: -2.96337e+008
  b: 1.98501e+009
  n: 5

matlab结果对前向或后向空间具有更好的精度

linspace(-296336583.4310038, 1985006328.0378299,5)

ans =  1.0e+09 *

  Columns 1 through 4

  -0.296336583431004   0.273999144436205   0.844334872303413   1.414670600170622

  Column 5

   1.985006328037830


linspace(1985006328.0378299,-296336583.4310038,5)

ans =

   1.0e+09 *

  Columns 1 through 4

   1.985006328037830   1.414670600170621   0.844334872303413   0.273999144436204

  Column 5

  -0.296336583431004

你可以看到这个数字非常相似,但......不完全一样。 你能帮忙解决这个问题吗?

0 个答案:

没有答案