0

When I use the aggregation framework to get values from my database and I got complex data structures, such as arrays of struct with doubles, I get inaccurate values.

I use the ToList() on my IAsyncCursor to get my values. The double values should be such as 13.23 and in the return json string the values are like 13.2300000001 or something like that. This is just a behavior if I use this complex structures of data.

What can I do against this Inaccuracy? Am I using the false classes and methods of the csharp api?

Tost
  • 51
  • 7
  • 1
    "What can I do against this Inaccuracy" - never directly compare two floats for equality. Always with some epsilon. – Sergio Tulentsev Jan 29 '18 at 10:10
  • I think, this doesn't explain why the mongodb c# api shows up that behavior. – Tost Jan 29 '18 at 10:21
  • 1
    I am pretty sure that if you try the same thing in mongodb shell, you'll get similar results. This is just how floating point numbers work, fundamentally, in every language. – Sergio Tulentsev Jan 29 '18 at 10:29
  • 1
    Try this in your console: `Console.WriteLine((0.1 + 0.2) == 0.3);` – Sergio Tulentsev Jan 29 '18 at 10:36
  • `'{ "Name" : "Some Name Value", "Value" : 123.63, "Child" : { "Name" : "Single Child", "Value" : 0.123, "arr" : [12.0, 13.0, 14.0, 15.0] }, "Children" : [{ "Name" : "Child1", "Value" : 1.123, "arr" : [12.1, 13.1, 14.1, 15.1] }, { "Name" : "Child2", "Value" : 2.1230000000000002, "arr" : [12.199999999999999, 13.199999999999999, 14.199999999999999, 15.199999999999999] }, { "Name" : "Child3", "Value" : 3.1230000000000002, "arr" : [12.300000000000001, 13.300000000000001, 14.300000000000001, 15.300000000000001] }] }'` - does that really explain that inconsistent behavior of mongodbs `ToList()`? – Tost Jan 29 '18 at 11:47
  • 1
    Why do you keep insisting that `ToList()` is the culprit? How do you _know_? – Sergio Tulentsev Jan 29 '18 at 11:50
  • Maybe I should use another more recommended method... What I don't understand is, that some double values are read "correctly" (Child)1 and others are not (Child2 or Child3) child2 should be: `{ "Name" : "Child2", "Value" : 2.123, "arr" : [12.2, ...` Thanks for your replies btw, helped me to understand it so far. – Tost Jan 29 '18 at 13:52
  • 1
    Some floating point numbers can be represented "exactly", others can not. That's what you observe here. Also, _do_ read the linked topic. – Sergio Tulentsev Jan 29 '18 at 13:54
  • Okay now I got it, thanks a lot. It's the numbers I choose, not the structure of my json. – Tost Jan 29 '18 at 13:57

0 Answers0