如何将大于 1e-8 的浮点值强制为 0

How do I force floating point values greater than 1e-8 to 0

我目前正在致力于实施矩阵前向归约,到目前为止它几乎通过了我所有的测试用例。但是我在舍入浮点值时遇到问题。我通过简单地添加 -1*a[j,col]/a[i,col] 来减少枢轴元素下方的非零行,其中 i = 枢轴,并且 j 在 i + 1 处初始化,向下迭代直到所有行都完成。

但是说我想要 1e-10 的浮点比较容差。如果 a[j,col] 中的值超过此公差,我如何强制将其设为零?

在某些情况下,在我的测试用例中,我的值在 1e-14 到 1e-15 之间,应该为零。我尝试过的当前案例如下所示,但这没有用。谁能指出我正确的方向? '

这是我第一次尝试比较浮点值,我读过它可能很困难,所以我希望有人能帮助我解决这个问题,因为它目前迫使我的应用程序停滞不前,直到它被修复.

var tolerance = 1e-10;
if (a[j, lead] < a[j, lead]*tolerance) { 
    a[j, lead] = 0; 
}

你可以试试这个方法

var tolerance = 1e-10;
var fraction = a[j, lead] - Math.Truncate(a[j, lead];
if (fraction<tolerance)
{
    a[j, lead] = 0;
}

不确定我是否完全理解您的条件,但如果您只关心指数,您可以检查指数是什么,并根据该检查是否符合您的标准。

你的头衔是"How do I force floating point values greater than 1e-8 to 0":

var tolerance = 1e-8;
bool compareExponents = 
(int) Math.Floor(Math.Log10(Math.Abs(a[j, lead]))) > 
(int) Math.Floor(Math.Log10(Math.Abs(tolerance))) ? true : false;

a[j,lead] = compareExponents ? 0 : a[j,lead];
//if the value(i.e a[j,lead]) is larger than the tolerance, i'm setting the value to 0. 
//otherwise, just keep the current value.
//
//1e^-15 > tolerance ==> 0
//1e^-8 > tolerance ==> a[j,lead]

如果你只关心指数不超过某个特定值,可以试试这个