Re: rounding off double values
- From: Jussi Piitulainen <jpiitula@xxxxxxxxxxxxxxxx>
- Date: 13 Aug 2008 15:00:01 +0300
jimgardener writes:
i am comparing elements of two double[] .one is an expected set like
double[] expected=new double[]{ 1.246,2.343,4.568};
while the second array is result of some calculation
public double[] mycalculations(){
double[] res=null;
.....//calculate the array
...
return res;
}
and can be
{ 1.246,2.3430000001,4.56800002 }
for practical purposes these two are equal,when you round off the
elements to 3 decimal places.if i want to unit test my code i need to
compare elements of both arrays .How do i do the rounding off?
DecimalFormat only helps me to print or display the numbers.I need
some way to compare like
for(int i=0;i<expected.length;i++){
assertEquals( roundoff( expected[i] ),roundoff( result[ i] ) );
}
can anybody suggest a way to do this?
If you know that all your numbers are of that magnitude, you may get
by with asserting that the absolute difference of the expected and
observed value is smaller than a threshold, like so:
assert(Math.abs(result[i] - expected[i]) < 0.00000001)
This fails with numbers very far from 0, where a negligible difference
can be much larger, and numbers very close to 0 where that threshold
is already huge compared to the numbers themselves. Think of 1e14 and
1e-14. That's where floating points becomes scary, but maybe you don't
need to go there. Two terms to search for are "absolute error" and
"relative error".
(There is a concept of ulps, though: units in the last position. It is
possible to find out how many floating point numbers there are between
the expected and observed value. They are numerically much denser near
zero than far from zero, but this seems to measure whether the program
worked as well as it can given that you use floating point.)
.
- References:
- rounding off double values
- From: jimgardener
- rounding off double values
- Prev by Date: Re: Responsive java application on windows ?
- Next by Date: Re: rounding off double values
- Previous by thread: Re: rounding off double values
- Next by thread: Re: rounding off double values
- Index(es):
Relevant Pages
|