I'm running some JS through googles closure compiler and noticed something about how it handles numbers. It seems that they are converted into something other than base 10 and I can't figure out what it is.
javascript:(function(){
var x = 30000;
console.log(x);
})();
Results in:
(function(){console.log(3E4)})();
How is 3E4 == 30000?
It's callled Scientific notation, especially the "E notation" part is what you're after.
Basically, aEb === a * Math.pow(10, b) (though this would be a syntax error - a and b have to be literals, b even has to be an integer).
3 * Math.pow(10, 4) === 30000; // true
The 3 and 4 are just in base 10. This has little to do with bases in fact.
The 3e4 is the same as "saying" 3 multiplied by 4 orders of magnitude, or a 3 with 4 zeros.
Related
I am building a factorization program and I would like to change each BigInt type to regular Numbers when number <= Number.MAX_SAFE_INTEGER.
Instead of coding two functions for each case, it would be nice if I could keep it all into one function which could vary variables types accordingly (something like let myVar = 3n || 3 I guess).
function Factorize(dividend) {
let divisor = 2n;
//if number <= Number.MAX_SAFE_INTEGER then let divisor = 2. Same for all other bigInts.
let method1 = [], method2 = [];
while (dividend > 1n) {
if (dividend % divisor === 0n) {
method1.push(`${divisor}`);
method2.push(`${dividend} / ${divisor}`);
dividend /= divisor;
} else {
divisor++
};
};
return {
default: method1,
detailed: method2,
get isPrime() {
return this.default.length === 1 && this.default[0] !== 2;
}
};
};
const number = parseInt(prompt());
console.log(Factorize(BigInt(number)));
Thanks for your help.
What's the difficulty? Your comment contains half the required code already:
if (dividend <= Number.MAX_SAFE_INTEGER) {
divisor = 2;
dividend = Number(dividend);
}
And then you only need to replace the two strict equality comparisons === 0n and !== 2 with their non-strict variants. 0 == 0n returns true, 0n === 0n returns false.
Some other things worth mentioning:
(1) This method for factorization is extremely slow. There are prime numbers well below Number.MAX_SAFE_INTEGER for which this will take months. Depending on your use case, limiting the input size or implementing some sort of timeout (e.g., returning an error if a certain number of iterations wasn't enough to find the complete result) may be more important than supporting BigInts at all. (For inputs that have only small prime factors, even extremely huge inputs will still terminate quickly, so it's certainly possible to exceed Number range (even Number.MAX_VALUE) while still only taking a few milliseconds.)
(2) Using parseInt to get your input means that you're limiting yourself to Number precision; converting that Number to a BigInt afterwards doesn't bring the lost bits back. For example, if someone enters '12157665459056928801' (which is 3n ** 40n), parseInt will truncate that and your program will hence compute the wrong result. To avoid that, use the fact that the BigInt() constructor can convert strings directly, i.e.: BigInt(prompt()).
(3) While it's sometimes possible to write code that can work on both Numbers and BigInts, doing so is generally not recommended (and often not even useful), because the two types of values (intentionally!) behave differently in a number of ways (otherwise we wouldn't need both of them), so there is a large risk of such code not doing what you think it'll do. In this particular case it should be okay; I'm just advising not to generalize from this example.
How can I initialise a variable in javascript to the biggest possible number? I am looking for an equivalent of:
Integer.MAX_VALUE --> Java
INT_MAX --> C
int.MaxValue --> C#
With the new added ECMAScript feature MAX_SAFE_INTEGER
console.log(Number.MAX_SAFE_INTEGER)
var i = Number.POSITIVE_INFINITY
console.log("infinity:", i)
var max = Number.MAX_SAFE_INTEGER
console.log("max:", max)
According to the MDN documentation Number.MAX_VALUE returns the biggest number possible in Javascript smaller than infinity.
Since it is larger than the maximum safe integer (Number.MAX_SAFE_INTEGER = 2 ^ 53 - 1 vs 2 ^ 1024 for Number.MAX_VALUE), it is best represented using the BigInt object which appends n to the end of the value. i.e.:
const maxSafeValue = BigInt(Number.MAX_VALUE);
// returns 17976...n
If you want to type less:
var i = 1/0
console.log(i) // Shows 'Infinity'
I was just curious, whether a number in JavaScript can ever reach Infinity.
The range of JavaScript numbers is pretty good enough -- 2 to the power of 64 different numbers, which is about 18 Quintilian (an 18 with 18 zeros after it). That’s a lot.
Now, I've few questions here:
What would really happen when a number grows beyond that range? Would JavaScript refer it as a new Infinity number?
What are all the scenarios in JavaScript, where the value Infinity could be assigned to a variable in runtime?
Let's look at a code example,
Attempting to write a method incrementNumToInfinity() to increment value of a certain number of times, so that a === b can evaluate to be true (also, to look at other possible scenarios, where the JavaScript Engine could assign the value Infinity to a variable in runtime).
var a = 1000; // a positive number
var b = Infinity;
console.log(a === b); // It returns false, that's expected
function incrementNumToInfinity(num) {
// Logic to convert our variable num into Infinity
return num;
};
a = incrementNumToInfinity(a); // Input: 1000, Expected output: Infinity
console.log(a === b); // Should return true
Can a number in JavaScript ever reach to Infinity in runtime?
It is possible at run time to get a number which is the result of a computation and which has for value Infinity. Nina Scholz has shown one such case: if you do x = 1 / 0, x will have for value Infinity.
What would really happen when a number grows beyond that range [i.e beyond the range JavaScript can handle]? Would JavaScript refer it as a new Infinity number?
We can try it. Number.MAX_VALUE is the maximum floating point number that JavaScript can represent. If you run this:
Number.MAX_VALUE + 1
You get a big number but not Infinity. What's going on there? Hmm, on a hunch let's try this:
Number.MAX_VALUE + 1 === Number.MAX_VALUE
The result is true. Say yhat? The problem is that floating point numbers have a limited precision, when I add 1 to Number.MAX_VALUE there isn't enough precision to register the increment.
If you try this:
Number.MAX_VALUE * 2
Then you get Infinity.
What are all the scenarios in JavaScript, where the value Infinity could be assigned to a variable in runtime?
"all the scenarios"... hmm... There are multiple issues with producing an enumeration of all the scenarios. For one thing, it is not clear what criteria should distinguish one scenario from one another. Is -Math.log(0) a different scenario from 1 / 0. If so, why? Then there's the issue that JavaScript engines have quite a bit of leeway to implement math functions. For instance, Math.tan is specified like this in the current draft:
Math.tan(x)
Returns an implementation-dependent approximation to the tangent of x. The argument is expressed in radians.
If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is -0, the result is -0.
If x is +∞ or -∞, the result is NaN.
It does not mandate a value for Math.tan(Math.PI / 2) If you recall your trigonometry classes, pi / 2 is 90 degrees and at that angle the tangent is infinite. Various versions of v8 have returned Infinity or a very large positive number. (See this question.) The specification does not mandate one result over the other: implementations are free to choose.
So practically if you start with a set of cases that you know mathematically should produce Infinity, you don't know whether they will actually produce that until you try them.
The part of your question with the incrementNumToInfinity function is not completely clear to me. You seem to be asking whether you can reach infinity simply by incrementing a number. It depends on what you mean. If you mean this:
let x = 0;
while (x !== Infinity) {
x++;
}
This will never terminate. x won't ever reach beyond Number.MAX_SAFE_INTEGER + 1. So it won't reach Infinity. Try this:
let x = Number.MAX_SAFE_INTEGER + 1;
x === x + 1;
You'll get the result true. That's again running into precision problems. The increment of 1 is not big enough to make a difference within the precision available to you.
Changing the increment to 2, 5, 10 or 10000000 does not really fix the issue, it just changes how far you can go before your increment no longer makes any difference.
Can a number in JavaScript ever reach to Infinity in runtime?
Assume your program does not have memory leak. I believe it can reach Infinity.
console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991
console.log(Number.MAX_VALUE)
// 1.7976931348623157e+308
var i = Number.MAX_SAFE_INTEGER
while (i != Infinity) {
i += Math.pow(10, 307)
console.log(i)
}
// 1.0000000000000005e+307
// 2.000000000000001e+307
// 3.0000000000000013e+307
// 4.000000000000002e+307
// 5.000000000000002e+307
// 6.000000000000003e+307
// 7.000000000000003e+307
// 8.000000000000004e+307
// 9.000000000000004e+307
// 1.0000000000000004e+308
// 1.1000000000000004e+308
// 1.2000000000000003e+308
// 1.3000000000000003e+308
// 1.4000000000000003e+308
// 1.5000000000000002e+308
// 1.6000000000000002e+308
// 1.7000000000000001e+308
// Infinity
The ratio of the square root of a square multiplied by PI of the same square subtracting PI to account for infinite decay as it approaches infinity, equals infinity. Or proving Archimedes wrong and right at the same time. PI and square are equivalent because neither will ever reach 0. This phenomenon also explains the zero boundary in the Pythagorean theory where A squared + B squared = c squared while approaching infinity.
Math.sqrt(1) / (Math.PI * ((Math.sqrt(1))) - Math.PI)
This is in result to the Fox and Duck Riddle. As the duck moves 1r of the distance to the pond the fox moves 180deg or the sum equivalent of the squares of its opposing and adjacent angles, we are give the square 2^2 (the travel distance from the center of the pond) Square root PI to the given 1:4 ratio therefor the hypotonuse of the triangle over pi - pi = Infinity or a 1:1 relationship with opposing vectors at any specific point.
ad 2:
What are all the scenarios in JavaScript, where the value Infinity could be assigned to a variable in runtime?
You could take a division with zero.
var x = 1 / 0;
console.log(x);
I am trying to Math.floor a scientific notation, but at one point the number gets too big and my current method doesn't work anymore. This is what I am using atm
var nr = (number+"").length - 4;
if( nr > 1 ) {
nr = Math.pow( 10, nr );
number= Math.floor(number/nr)*nr;
number= number.toExponential(3);
}
When it becomes a scientific notation by default, I think that's e20+, than my .length method doesn't work anymore since the length it returns isn't accurate. I can think of a work around, and that's to find out the number after e, and update my nr to Math.floor it properly, but it seems like so much work to do something so simple. Here's an example number 8.420960987929105e+79 I want to turn this into 8.420e+79, is there a way I can Math.floor the third decimal point always, no matter what the number is? As it stands when I use toExponential(3) it always rounds the number. My numbers can get as high as e+200 easily, so I need an easier way of doing what I'm currently doing.
Edit: managed to find a work around that works besides Connor Peet's answer for anyone who wants extra options
var nr = 8.420960987929105e+79+"";
var nr1 = nr.substr(0,4);
var nr2 = nr.substr(4, nr.length);
var finalNr = Number(nr1 + 0 + nr2).toExponential(3);
This way is more of a hack, it adds a 0 after the 4th number so when toExponential rounds it up, it gets 'floored' pretty much.
I wrote a little snippet to round a number to a certain number of significant figures some time ago. You might find it useful
function sigFigs(num, figures) {
var delta = Math.pow(10, Math.ceil(Math.log(num) / Math.log(10)) - figures);
return Math.round(num / delta) * delta;
}
sigFigs(number, 3); // => 8.420e+79
I failed to find any constant in JS language which represents MAX UINT 32
Does it exists? I can have hardcoded the number itself, but i prefer to go in the more appropriate path of coding
For integers, Number.MAX_SAFE_INTEGER would be appropriate, as it's the maximum safe integer in JavaScript (2^53 – 1). The 53 power comes from how the double-precision floating-point numbers work. Those are also used in JavaScript to store numbers.
// In the safe integers zone:
const a = Number.MAX_SAFE_INTEGER - 1;
const b = Number.MAX_SAFE_INTEGER - 0;
console.log(a); // 9007199254740990
console.log(b); // 9007199254740991 (b + 1)
console.log(a === b); // false
// Outside the safe integers zone:
const x = Number.MAX_SAFE_INTEGER + 1;
const y = Number.MAX_SAFE_INTEGER + 2;
console.log(x); // 9007199254740992
console.log(y); // Also 9007199254740992, because precision....
console.log(x === y); // true
By the way, imagine that would happen if your iteration meets this kind of unsafe zone - infinite loop.
See also:
Number.EPSILON for the difference between 1 and the smallest floating point number greater than 1;
Number.MAX_VALUE for maximal number representable in JavaScript - not integer, but floating point.
Number.MIN_SAFE_INTEGER - for minimal safe integer (negative) in JavaScript.
Number.MIN_VALUE - for minimal negative number overall (floating point).
In some cases it's nicer to just use use Number.POSITIVE_INFINITY (or Number.NEGATIVE_INFINITY for negative), like when finding max/min values - for empty set you would get this not quite valid numerical value, that you can more easily notice and understand.
On linked pages you can also find other interesting stuff, like Number.isSafeInteger function to check whenever number is safe integer.
It does not exist, however you can have Max Numeric Value returned by Number object
You can see it here
alert(Number.MAX_VALUE);
Reference
javascript was no ints every number is a floating point number which is of class Number. The max value of that is Number.MAX_VALUE but that is almost certainly not what you are looking for (Number.MAX_VALUE = 1.7976931348623157e+308)
Try This:
<script>
function myFunction()
{
document.getElementById("demo").innerHTML=Number.MAX_VALUE;
}
</script>
Description
The MAX_VALUE property has a value of approximately 1.79E+308. Values larger than MAX_VALUE are represented as "Infinity".
Because MAX_VALUE is a static property of Number, you always use it as Number.MAX_VALUE, rather than as a property of a Number object you created.
Example: Using MAX_VALUE
The following code multiplies two numeric values. If the result is less than or equal to MAX_VALUE, the func1 function is called; otherwise, the func2 function is called.
if (num1 * num2 <= Number.MAX_VALUE) {
func1();
} else {
func2();
}