Extend Math.log to allow for bases != e

As Math.log currently stands, it’s a bit useless. It only calculates natural logarithms (base e).  We can easily modify it however, to calculate logarithms of any base:
Math.log = (function() {
var log = Math.log;
return function(n, a) {
return log…


This content originally appeared on Lea Verou’s blog and was authored by Lea Verou

As Math.log currently stands, it’s a bit useless. It only calculates natural logarithms (base e).  We can easily modify it however, to calculate logarithms of any base:

Math.log = (function() {
	var log = Math.log;
	return function(n, a) {
		return log(n)/(a? log(a) : 1);
	}
})();

We can now specify the base as a second parameter, or still use the default one (Math.E) if we don’t specify one, so older scripts won’t break or if we want a shortcut to the natural logarithm. ;)


This content originally appeared on Lea Verou’s blog and was authored by Lea Verou


Print Share Comment Cite Upload Translate Updates
APA

Lea Verou | Sciencx (2009-03-26T00:00:00+00:00) Extend Math.log to allow for bases != e. Retrieved from https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/

MLA
" » Extend Math.log to allow for bases != e." Lea Verou | Sciencx - Thursday March 26, 2009, https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/
HARVARD
Lea Verou | Sciencx Thursday March 26, 2009 » Extend Math.log to allow for bases != e., viewed ,<https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/>
VANCOUVER
Lea Verou | Sciencx - » Extend Math.log to allow for bases != e. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/
CHICAGO
" » Extend Math.log to allow for bases != e." Lea Verou | Sciencx - Accessed . https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/
IEEE
" » Extend Math.log to allow for bases != e." Lea Verou | Sciencx [Online]. Available: https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/. [Accessed: ]
rf:citation
» Extend Math.log to allow for bases != e | Lea Verou | Sciencx | https://www.scien.cx/2009/03/26/extend-math-log-to-allow-for-bases-e/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.