[CSHARP-1047] Losing precision in conversion from float to BsonDouble Created: 21/Aug/14  Updated: 22/Sep/14  Resolved: 22/Sep/14

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: Marc Cortada Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: bson
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Backwards Compatibility: Fully Compatible

 Description   

We could improve the BsonDouble type converting values from a float type without losing precision like decimal types (decimal type in C# solves the losing precision converting some numeric values).

Example:

With the actual implementation, the function BsonTypeMapper.MapToBsonValue returns a BsonDouble with precision lost if the parameter passed is a float. See the following new test case:

float value2 = 1.3f;
BsonDouble secondBsonValue = (BsonDouble)BsonTypeMapper.MapToBsonValue(value2);
BsonDouble expectedResult = 1.3d;
Assert.AreSame(expectedResult, secondBsonValue);

The test case result is:

MongoDB.Bson.Tests.BsonTypeMapperTests.TestMapBsonDouble:

Expected: same as <1.3>

But was: <1.2999999523162842>

Also the comparison is not entirely accurate. See the following code of a console test code:

float value = 1.3f;
var bsonValue = (BsonDouble)BsonTypeMapper.MapToBsonValue(value);
bool result1 = (value == bsonValue);
Console.WriteLine("Case 1: Original:

{0}, converted: {1}. AreSame: {2}. ¿?¿", value, bsonValue, result1);
var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);
bool result2 = (value == bsonDouble);
Console.WriteLine("Case 2: Original: {0}

, converted:

{1}. AreSame: {2}. ¿?¿ ", value, bsonDouble, result2);
Console.ReadKey();

Outputs:

Case 1: Original: 1,3, converted: 1.2999999523162842. AreSame: True. ¿?¿
Case 2: Original: 1,3, converted: 1.2999999523162842. AreSame: True. ¿?¿

Proposed solution:

Use the decimal type as an intermediate cast.

This code converts values without losing precision.

float f = 3.2f;
double d = (double)(decimal)f;
double d2 = (double)f; // Loss
Console.WriteLine("Original float: {0} and converted double: {1}

", f, d);
Console.WriteLine("Original float:

{0}

and converted double without intermediate decimal:

{1}

", f, d2);

Output:
Original float: 3,2 and converted double: 3,2
Original float: 3,2 and converted double without intermediate decimal: 3,2000000
4768372

I needed solve it and I have a valid implementation which passes the test cases and I’m able to pull request shortly.



 Comments   
Comment by Marc Cortada [ 22/Sep/14 ]

Thank you Robert for the detailed explanation and lesson . You are right: it's a reflection, not a loss of precision.
I'll close the pull request in Git.

Comment by Robert Stam [ 22/Sep/14 ]

The behavior you are observing is NOT a loss of precision, but rather just a reflection of the fact that base-2 floating point numbers can't accurately represent decimal fractions.

The C# driver converts float to BsonDouble with NO loss of precision, which is true simply because the C# language (or rather, the representation of 32-bit and 64-bit floating point numbers) guarantees that floats can be converted to doubles with no loss of precision.

Consider the following sample code:

float f = 1.3f;
BsonDouble x = (BsonDouble)BsonTypeMapper.MapToBsonValue(f); // NO loss of precision
BsonDouble y = (BsonDouble)BsonTypeMapper.MapToBsonValue(1.3d); // 1.3d is NOT the same number as 1.3f
BsonDouble z = (BsonDouble)BsonTypeMapper.MapToBsonValue((double)(decimal)f); // two rounding errors
 
Console.WriteLine("f == x.Value is {0}", f == x.Value);
Console.WriteLine("f == y.Value is {0}", f == y.Value);
Console.WriteLine("f == z.Value is {0}", f == z.Value);
Console.WriteLine("1.3f == 1.3d is {0}", 1.3f == 1.3d);

which outputs:

f == x.Value is True
f == y.Value is False
f == z.Value is False
1.3f == 1.3d is False

The first result is True precisely because a float can be converted to a BsonDouble with NO loss of precision.

The second result is False because 1.3d is NOT the same number as 1.3f. Neither constant is exactly equal to 1.3, because 1.3 does not have an exact representation in base-2 floating point numbers. The reason they are NOT the same value is that 1.3d is represented using 64 bits, while 1.3f is represented using 32 bits. So 1.3d is a closer approximation to the decimal number 1.3 than 1.3f is, and therefore is not the same value.

The third result is False because converting from float to decimal and then to double doesn't actually accomplish what you intend, or rather, while it might accomplish what you want in one example, it is the wrong thing to do in general because the end result is not the same number you started out with. When you convert from float to decimal you introduce rounding errors as binary fractions are converted to decimal, and when you convert from decimal to double you introduce a second set of rounding errors.

The final result is False just to illustrate that the compiler agrees with me that 1.3f and 1.3d are not the same number.

I'm going to close this ticket as "Works as Designed".

Comment by Craig Wilson [ 25/Aug/14 ]

Thanks Marc. We are discussing the implications of doing this and will get back to you.

Comment by Marc Cortada [ 25/Aug/14 ]

Pull request is done!
https://github.com/mongodb/mongo-csharp-driver/pull/188

Generated at Wed Feb 07 21:38:31 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.