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();
}
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.
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 using various JavaScript Math functions and, due to floating point numbers, these functions occasionally return values that are either 0.000000001 larger or smaller than the correct integer answer. I am looking to set up an if-else statement for said functions that will return the correct integer answer should the value be within some small range of an integer (note that the non-specificity of said integer is of utmost importance).
So I am asking, is there a way, using JavaScript, to determine if the value returned from a math function (Math.cbrt() for example) is within some margin of a non-specific integer?
NOTE: I have tried using Number.EPSILON in a function which calculates the x-th root of a number like so
var index = $('#Index').val();
var radicand = $('#Radicand').val();
var powerXroot = Math.pow(radicand,(1/index))+(Number.EPSILON * Math.pow(radicand,(1/index)));
but it doesn't work for all indicies.
You can use Math.round() to get the nearest integer to the result. If this integer is within 0.000000001 of the result, replace the result with the integer instead.
Say, you have computed var x = ... and want to make it an integer if it's sufficiently close to one.
function roundIfAlmostInteger(x) {
if (Math.abs(x - Math.round(x)) < 0.000000001) {
x = Math.round(x);
}
return x;
}
Illustration:
x = 2.3 - 0.1 - 0.2; // now x is 1.9999999999999998
x = roundIfAlmostInteger(x); // now x is 2
I have a JavaScript calculator which uses the Math.cbrt() function. When I calculate the cube root of 125 it returns 4.999999999999999. I understand that I could use Math.round() to round any answers that this function returns to integer values, but I do not want to do that exactly. Is there a way to use this if and only if the result of calculation is some number followed by a string of 9s (or something similar like 4.99999998 perhaps) after the decimal?
What you are dealing with is the frustration of floating point numbers in computing. See the Floating Point Guide for more information on this critical topic.
The short version:
Certain non-integer values cannot be represented accurately by computers, so they store a value that is "near enough". Just try evaluating 3.3 / 3 in your favourite REPL.
Say what?!
Computers are supposed to be perfect at this numbers/math thing, right? Can I trust any answer they give me?
Yes, for integers, they are pretty much perfect. But for non-integer calculations, you should assume that answers won't be exact, and account for these floating point errors.
The solution in Javascript
In newer versions of Javascript, you have a defined constant Number.EPSILON, which is the smallest difference between the actual number and the approximation that it can actually store.
Using this, you can multiply that constant by the result you get and add it to the result and you should get the exact value you require.
function cbrt(n) {
return Math.cbrt(n) + (Number.EPSILON * Math.cbrt(n));
}
Alternatively, you can use the rounding behaviour of the .toFixed() method on numbers together with the parseFloat() function if you only care about numbers up to a certain number of decimal places (less than 20).
function num(n, prec) {
if (prec === void 0) prec = 8; // default to 8 decimal places
return parseFloat(n.toFixed(prec));
}
var threshold = 0.999; // set to whatever you want
var fraction = result % 1;
if (fraction >= threshold) {
result = Math.round(result);
}
For instance, I have float 1.1111111111 and need to get 11111111111 and 10.
I want to avoid functions, which may change part after point as I need it to show metric prefixes.
It may look simple with strings, I am just not sure if it is a proper way in JavaScript.
The modular division operator '%' can be used to get the remainder of a division in JS. This means that if we perform the modular division of a floating point number by 1, we get the value after the decimal point. Further, if we build a loop where we multiply by 10 until there is no longer anything after the decimal point, we can find the smallest power of ten we can multiply the original number by to get an integer.
Example below:
function getE(floatingPointValue)
{
var x = floatingPointValue;
var digitsAfterDecimal = 0;
while(x % 1 != 0)
{
x = x * 10;
digitsAfterDecimal++;
}
return x.toString() + " *10^-" + digitsAfterDecimal;
}
Fiddle: http://jsfiddle.net/L8XtP/2/
Hope this helps!