Reputation: 5011
I have a program which prints out a matrix with very small values. An example of my matrix is
0.00000000000000004 0.12300000000000000
0.00000000011111114 0.00000000000038544
What I would like to do is compare each value with zero
and accept it to be zero
with specific accuracy, which is 9 decimal places. In other words, if a number has 9 zeros
as its first decimal values, I want to consider it as a zero
, otherwise not.
I have searched a lot but really found nothing about it. Any ideas?
Upvotes: 0
Views: 91
Reputation: 16107
My idea is similar to what @MicroVirus has mentioned in his comment. You can simply compare it to a specific number:
if(num < 1E-9 && num > -1E-9)
num = 0;
or
if(num * 1E9 < 1 && num * 1E9 > -1)
num = 0;
Upvotes: 2
Reputation: 5477
As I noted in my comment, you can simply compare the float f
via -1e-9 < f < 1e-9
.
The you need both the positive and negative boundary to ensure it works properly for positive and negative numbers. You use 1e-9
and not 1e-10
because if a number is smaller than 1e-9
, a number with 8 decimals 0, then it has 9 decimals or more zero.
Do note that due to float rounding of 1e-9
when going from decimal to binary, you might see some rounding error.
Upvotes: 5