Skip to content

Instantly share code, notes, and snippets.

@jiggzson
Created May 17, 2018 02:12
Show Gist options
  • Save jiggzson/7037516b37b35437545c1c31304e6bfa to your computer and use it in GitHub Desktop.
Save jiggzson/7037516b37b35437545c1c31304e6bfa to your computer and use it in GitHub Desktop.
This calculates the log of a number and is independent of Math.log. This can be used with a big number or bigInt library to calculate a custom precision value of log.
//TODO: Still depends on Math.sqrt and Math.pow
var factorial = function(n) {
++n;
var r = 1;
while(n-->1)
r*=n;
return r;
};
var PI = function(n) {
n = n || 30;
var k = Math.sqrt(2)*2/9801;
var sum = 0;
for(var i=0; i<n; i++) {
sum += (factorial(4*i)*(1103+26390*i))/
(Math.pow(factorial(i), 4)*Math.pow(396, 4*i));
}
return 1/(sum*k);
};
var qlog = function(x, e=1e-16) {
var a, b, c, d, de, ans, prev, k;
a = x-1;
b = x+1;
c = (a*a)/(b*b);
d = 2*a/b;
ans = 0;
k = 0;
prev = 0;
do {
ans += (1/(2*k+1))*Math.pow(c, k);
de = ans - prev;
prev = ans;
k++;
}
while(de >= e)
return ans*d;
};
var log = function(x) {
return ln(x)/ln(10);
};
//arithmatic mean
var M = function(x, y) {
var a, b, d, e=1e-20;
do {
a = (x+y)/2;
b = Math.sqrt(x*y);
d = a-b;
x = a;
y = b;
}
while(d >= e)
return x;
};
var calc_m = function(p, x) {
var m = 1;
var p2 = p/2;
while(x*Math.pow(2, m) < Math.pow(2, p2))
m++;
return m;
};
var log = function(x, p=25) {
var m, LN2, pi;
LN2 = qlog(2);
m = calc_m(p, x);
pi = PI();
return pi/(2*M(1, Math.pow(2, 2-m)/x))-m*LN2;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment