Standard
Standard

Reputation: 1512

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.

Upvotes: 1

Views: 1202

Answers (3)

Phil H
Phil H

Reputation: 20141

Code

Values in practice:

var x = Math.pow(10,33);           // x = 1.0000000000000001e+33
var exponent = -18*x;              // exponent = -1.8000000000000002e+34
var deci = Math.pow(10, exponent); // deci = 0
var logged = Math.log(deci);       // logged = NaN (-Infinity)
var result = logged/Math.log(10);  // result = NaN (-Infinity)

The problem is that floating point values can have decimal exponents in the range -308 to +308 (approximately, it's really all in binary), and your exponent is approximately 18,000,000,000,000,002,000,000,000,000,000,000.

Maths

Maths gives us log(xy) = y.log(x). And that logb(b) = 1. Thus,

   log10(10-18x) = -18x.log(10) = -18x.

So the maths lesson is that "logging X (base b)" and "raising b to the power of X" are inverse operations.

Upvotes: 0

Timothy Shields
Timothy Shields

Reputation: 79441

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)

Upvotes: 2

TheNorthWes
TheNorthWes

Reputation: 2739

You are overflowing the maximum integer allowed in JavaScript by quite a bit.

Max int in JS

Wolfram proof because why not

You are going to need a big number extension of JavaScript, which SO has many posts about. See here for what appears to be unlimited integer math

More posts like this can be chased starting here

Upvotes: 1

Related Questions