Search code examples
javascriptmathlogarithm

Simple formula in Javascript is infinity


I've following formula in Wolfram:

log base 10 of (10^-18x)

WolframLink (with x example)

First of all Log Function:

function getLog(y) {
    return Math.log(y)/Math.log(10);
}

Now I'm trying to get my value:

var x = Math.pow(10,33);
var faktor = getLog(Math.pow(10,-(18*x)));
console.log(faktor);

console gives -Infinity

What is wrong about my code? Thanks for help.


Solution

  • Your computations are causing floating point underflow. A floating point number is roughly represented as 0.<mantissa> × 2<exponent>, so that the distribution of log(|x|) for representable values x is uniformly dense. Both the mantissa and exponent have a certain number of bits allocated for them. The exponent of the representation can only become so small, and if you try to make it smaller than the minimum, the representation is forced to round to 0.

    You can instead perform your computations in logspace using these identities. A few of these are listed here.

    • log(x × y) = log(x) + log(y)
    • log(x / y) = log(x) - log(y)
    • log(xy) = y × log(x)