Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

float rounding mistake when optimizing Rails #448

Closed
toaster opened this issue Dec 8, 2017 · 3 comments
Closed

float rounding mistake when optimizing Rails #448

toaster opened this issue Dec 8, 2017 · 3 comments

Comments

@toaster
Copy link

toaster commented Dec 8, 2017

Oj version: 3.3.9
Ruby version: 2.3.3
Rails version: 5.0.1

[1] pry(main)> f = -1.7976931348623157e+308
=> -1.7976931348623157e+308
[2] pry(main)> require 'rails'
=> true
[3] pry(main)> f.to_json
=> "-1.7976931348623157e+308"
[4] pry(main)> require 'oj'
=> true
[5] pry(main)> Oj.dump(f)
=> "-1.79769313486232e+308"
[6] pry(main)> Oj.default_options = {float_precision: 0}
=> {:float_precision=>0}
[7] pry(main)> Oj.dump(f)
=> "-1.7976931348623157e+308"
[8] pry(main)> Oj.optimize_rails
=> nil
[9] pry(main)> f.to_json
=> "-1.797693134862316e+308"

As you can see, the default Rails to_json does not round the number.
Oj rounds because of its float_precision but this can be turned of using float_precision: 0.
But when Oj optimizes the Rails implementation, it uses a precision independent from its default_options and not fully compatible to the standard Rails behaviour.

@ohler55
Copy link
Owner

ohler55 commented Dec 8, 2017

I can bump up the precision for the optimized version to 17 significant digits but you will then find that the 17th digit is sometimes different. Optimization uses a different conversion from a float (C double) to a string. Any more than 16 digits will vary since the binary encoding for a float does not support more than 16 digits across all numbers. If exact behavior with rails out to 17 significant digits is more important than performance then the extra step of optimizing should not be taken.

@toaster
Copy link
Author

toaster commented Dec 8, 2017

Okay, I understand that.
We will skip the optimization part, then.

@ohler55
Copy link
Owner

ohler55 commented Dec 8, 2017

Thanks for understanding. Float precision has been trouble for quite a while.

@ohler55 ohler55 closed this as completed Apr 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants