-
Notifications
You must be signed in to change notification settings - Fork 6
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
fix nearest-neighbor rounding in Util.toFixed #35
Comments
The desired behavior (which I've implemented in Util.toFixed) is IEEE 754 "Round half away from zero" algorithm, see https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero. It treats positive and negative values symmetrically. It occurred to me that it would be nice to have a round function that behaves this way. |
Work completed. I added Util.roundSymmetric, and used it in Util.toFixed. I added documentation about the problem with Math.round, and references to the relevant IEEE 754 specs. Assigning to @jonathanolson to review. |
Summary for developers, which I also sent in an email and Skype: JavaScript’s Math.round uses “round half up” (https://en.wikipedia.org/wiki/Rounding#Round_half_up), which does not treat positive and negative numbers symmetrically. Example:
That behavior is problematic for PhET sims, where we want to treat positive and negative numbers symmetrically. I’ve added dot.Util.roundSymmetric, which treats positive and negative numbers symmetrically and uses "round half away from zero“ (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). Example:
Util.roundSymmetric is also used in Util.toFixed, so that formatting of numbers will also be treat positive and negative numbers symmetrically. Example:
Recommendations: • Don’t use Math.round unless you want “round half up” behavior |
Re:
I've added this section to the Code Review Checklist (https://github.com/phetsims/phet-info/blob/master/code_review_checklist.md): Common Errors
|
Re:
Addressing in phetsims/tasks#275. |
Looks good to me. The only case where it really otherwise deviates seems to be -0: Math.round( -0 ); // -0
roundSymmetric( -0 ); // 0 Feel free to close if it was just pending on review. |
@jonathanolson I purposely did not round -0 to -0 because generally we don't want to display -0 in sims. Do you disagree? Is the issue only with -0, or do you think that -1.2 should be rounded to -0? |
Sounds fine to me, just wanted to note it. |
I've noted the -0 behavior in the documentation, 65da3f5 |
Closing. |
Behavior of Math.round (and therefore dot.Util.toFixed) is currently:
Math.round(1.5) -> 2, Math.round(-1.5) -> -1.
This is not desirable for PhET sims. The desired behavior is one that treats positive and negative values symmetrically. Take care of this in dot.Util.toFixed.
The text was updated successfully, but these errors were encountered: