Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float to Double conversion - Best assertion in a unit test?

Given the statements

float f = 7.1f;
double d = f;

What can we assert in a unit test about d?


For example this does not work:

Console.WriteLine(d == 7.1d); // false
Console.WriteLine(d < 7.1d + float.Epsilon); // true by luck
Console.WriteLine(d > 7.1d - float.Epsilon); // false (less luck)

The best way I found so far is to convert the value back:

float f2 = (float)d;
Console.WriteLine(f2 == f); // true

Which would be the same as the brute way to say

Console.WriteLine(d == 7.1f); // 7.1f implicitly converted to double as above

This question is NOT about double and float precision in general but really JUST about the pragmatic question how a unit test can best describe the confines of d. In my case, d is the result of a conversion that occurs in code generated by light weight code generation. While testing this code generation, I have to make assertions about the outcome of this function and this finally boils down to the simple question above.

like image 863
citykid Avatar asked Dec 19 '12 12:12

citykid


People also ask

Can a float be converted to a double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .

What is unit test assert?

The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method under test. The Arrange section of a unit test method initializes objects and sets the value of the data that is passed to the method under test. The Act section invokes the method under test with the arranged parameters.


1 Answers

Your "best way" is asserting that your generated code returns something that is, within float's margin of error, 7.1. This may be what you want to check, in which case, carry on.

On the other hand, you might want to assert that your generated code returns specifically the result of casting 7.1f to a double, in which case you could do:

Console.WriteLine(d == (double)f);

This is more stringent - your test asserts that d is within a small range, while the above test asserts that d is a specific value.

It really depends on what you'll be using d for. If it's a case where things will go wrong if it's not the exact value, test the exact value, but if it's OK to be within a float of the value, check against the float.

like image 141
Rawling Avatar answered Oct 16 '22 16:10

Rawling