Float rounding (in JSON)

Sergey kornburn at yandex.ru
Thu Oct 13 21:06:42 UTC 2022


On Thursday, 13 October 2022 at 19:27:22 UTC, Steven 
Schveighoffer wrote:

Thank you Steven, for your very detailed answer.

> It doesn't look really that far off. You can't expect floating 
> point parsing to be exact, as floating point does not perfectly 
> represent decimal numbers, especially when you get down to the 
> least significant bits.

This is sad - because "exact" match is what I need in this toy 
example.

> But I want to point out something you may have missed:

Actually I've meant those things too :)

> But look also at f3, and how actually D is closer to the 
> expected value than with the other languages.
>
> If you want exact representation of data, parse it as a string 
> instead of a double.

Unfortunately it is not helped me in this task (which is pretty 
awkward): it parses some GeoData from JSON file. Then create 
representation of that data into string format and use hash from 
that string. Because they use the Hash - I need exact the same 
string representation to match the answer.

> I'm assuming you are comparing for testing purposes? If you 
> are, just realize you can never be accurate here. You just have 
> to live with the difference. Typically when comparing floating 
> point values, you use an epsilon to ensure that the floating 
> point value is "close enough", you can't enforce exact 
> representation.
>
> -Steve

Actually it was my attempt to implement the benchmark-game: 
https://programming-language-benchmarks.vercel.app/problem/json-serde

As you can see many languages have passed tests which I assume 
they have exactly same representation of that float numbers.
Maybe I am wrong and did not understand code from other 
realizations. But at least I test python and crystal and found 
pretty confusing their results (what you wrote about more 
accurate example of f3), but what surpsised me even more: they 
have exactly same confused results with those floating numbers.
That's why I've made a conclusion that maybe it is some special 
and declared behavior/rule for that and I just can't find how to 
replicate that "well known behavior" in D.




More information about the Digitalmars-d-learn mailing list