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

Bugfix: Improve polyfill function of log10 to return whole powers of 10 #5275

Merged
merged 2 commits into from Feb 20, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/core/core.helpers.js
Expand Up @@ -159,7 +159,13 @@ module.exports = function(Chart) {
return Math.log10(x);
} :
function(x) {
return Math.log(x) / Math.LN10;
var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
// Check for whole powers of 10,
// which due to floating point rounding error should be corrected.
var powerOf10 = Math.round(exponent);
var isPowerOf10 = (x / Math.pow(10, powerOf10)) === 1;

return isPowerOf10 ? powerOf10 : exponent;
};
helpers.toRadians = function(degrees) {
return degrees * (Math.PI / 180);
Expand Down
8 changes: 6 additions & 2 deletions test/specs/core.helpers.tests.js
Expand Up @@ -194,8 +194,12 @@ describe('Core helper tests', function() {

it('should do a log10 operation', function() {
expect(helpers.log10(0)).toBe(-Infinity);
expect(helpers.log10(1)).toBe(0);
expect(helpers.log10(1000)).toBeCloseTo(3, 1e-9);

// Check all allowed powers of 10, which should return integer values
var maxPowerOf10 = Math.floor(helpers.log10(Number.MAX_VALUE));
for (var i = 0; i < maxPowerOf10; i += 1) {
expect(helpers.log10(Math.pow(10, i))).toBe(i);
}
});

it('should correctly determine if two numbers are essentially equal', function() {
Expand Down