我有一个CV_32FC1类型的矩阵,我想限制它的精度。例如,它具有这样的值(value):

[0.00021743798, 0.000174778698, 0.00011652464, 5.826234e-005, 1.561136e-005]

但是我想限制它的精度,以使其看起来像这样(例如在Matlab中):
[0.0002, 0.0002, 0.0001, 0.0001, 0.0000]

我不是要寻找std::setprecision解决方案,而是要完全限制内部的矩阵值精度,因为在我的情况下,这将影响与其他矩阵的乘法。更改矩阵类型无济于事(至少)。我该怎么办?谢谢。

最佳答案

可能这些应该有用(做一些初步检查)

float customPrecision(float in)
{
     char buffer[15];
     int bufLen = sprintf(buffer, "%.4f", in);
     return atof(buffer);
}

恐怕要选择缓冲区大小,因为float可以使给您23位有效数,8位指数和1个符号位。 有人可以帮助您选择合适的缓冲区大小。

正如阿迪所建议的
float roundtoPrecision(float val,int precision)
{
     // Do initial checks
     float output = roundf(val * pow(10,precision))/pow(10,precision);
     return output;
}

int main()
{
    // your code goes here
    float a[] = {0.00021743798, 0.000174778698, 0.00011652464, 5.826234e-005, 1.561136e-005};

    for (int index = 0; index < 5; index++)
    {

        float val = roundtoPrecision(a[index], 4);
        cout << val << endl;
    }
    return 0;
}

09-10 05:46
查看更多