Javascript Infinity - javascript

Division by 0 gives this special value:
3/0 output:Infinity
You can’t play positive and negative infinity against each other:
Infinity - Infinity output:NaN (Why?)
It also turns out that “beyond infinity” is still infinity:
Infinity + Infinity output:Infinity(this is accepted)
5 * Infinity
Infinity(this is also accepted)
so why infinity-infinity evalutes to NaN?It should be infinity isn't it?Also i wanted to know why cant object be converted to primitive values?Sorry for posting two question at a time ,as this is the last question i can post.See here:
var obj = {
valueOf: function () {
console.log("valueOf");
return {}; // not a primitive
},
toString: function () {
console.log("toString");
return {}; // not a primitive
}
}
Number(obj) //TypeError: Cannot convert object to primitive values

That's how ∞ works in mathematics. Infinity itself is not a number, it is a concept. The general idea is that
∞ + x = ∞ ∀ x
∞ is, obviously, infinitely big. If you subtract an infinitely big thing from another infinitely big thing, you can't define what you have left. If the first infinity is bigger, you'll get a negative result, but if it's smaller then the result will be positive (basic rule of subtraction), but since both are infinitely big you have no way of knowing which is bigger (unless more information is given, such as the context leading to these infinities*). Therefore, as far as the computer is concerned, ∞ - ∞ is mathematically undefined, or Not a Number.
* Example: Let x = the sum of all positive integers, and y = the sum of each positive integer doubled. In this case, we can say that y > x, even though both are infinity.

Because it's an indeterminate form, so it's not infinity. NaN reflects this the best way possible.
http://en.wikipedia.org/wiki/Indeterminate_form
Related question:
https://math.stackexchange.com/questions/60766/what-is-the-result-of-infinity-minus-infinity

var A = 1/0
var B = 2 * A
var c = B - A
Note that even though B = 2 * A, still A = B (2 * infinity is still infinity, so they are both infinity), so what do you expect C to be? infinity or 0?
Infinity is not really a number, mathematically speaking. Though IsNaN(1/0) = false.

Related

Javascript: Confused about usage of Infinity

I'm doing some practice problems to stay fresh and I've never really used Infinity before in my job. The question is:
Find maximum difference between two numbers in the given array. Also, the second number must be larger than the first one.
My solution was:
var maxProfit = function(prices) {
let min = 0;
let max = 0;
for (var x = 0; x < prices.length; x++) {
min = Math.min(min, prices[x]);
max = Math.max(max, prices[x] - min);
}
return max;
};
But it comes back incorrect and I'm not sure why. When looking at the accepted solutions, one of them has the same code as me except the initialized value of min is Infinity, ( let min = Infinity ) rather than 0. I'm not really sure how or why that works.
Because 0 is always smaller than any other positive number. Therefore unless you have negative prices, the minimum will be 0. You can exchange 0 with any other larger number, e.g. 1000, and even then the function might return the wrong minimum because the smallest price in the array might only be 1001. So as an initial value you can either take one of the array values (e.g. the first one), or you take Infinity cause that's greater than any other number, and thus it will never be the result unless the array is empty. And in that case, Infinity is a proper result.

Comparing big numbers in Javascript

I've got two numbers that I want to compare. The numbers in the following example are the result of 26^26 computed in two different systems. One of which is my javascript code.
However, when comparing the two numbers I end up with something like this:
AssertionError [ERR_ASSERTION]: 4.0329146112660565e+26 == 4.0329146112661e+26
They're obviously not equal, but theoretically they should.
What's the proper way to perform equality on big numbers in javascript (even if it's an approximation)?
If what you're trying to do is determine if two numbers are practically equivalent you'll have to come up with your margin of error. One way to do this is to compute the difference between the numbers and then determine if that difference is significant or not.
So, taking your numbers from before, we could evaluate the difference between these numbers through subtraction. Since we don't really care about the sign of this difference, I'll go ahead and get the absolute value of the difference.
Math.abs(4.0329146112660565e+26 - 4.0329146112661e+26) === 4329327034368
(Sidenote: Now is not the time to explain why, but the == operator in JavaScript has confusing and error-prone behavior, use === when you want to compare values.)
That difference is a HUGE number, but related to how big our numbers are in the first place, it's rather insignificant. Intuitively, I'm tempted to divide the difference by the smallest of our original numbers like so:
4329327034368 / 4.0329146112660565e+26 === 1.0734983136696987e-14
That looks like a pretty small number. Repeat that same operation with a bunch of values and you should be able to determine what you want your margin of error to be. Then, all you'll have to do is perform the same operations with arbitrary numbers and see if that "difference ratio" is small enough for you.
function similar(a, b) {
let diff = Math.abs(a - b);
let smallest = Math.min(Math.abs(a), Math.abs(b));
let ratio = diff / smallest;
return ratio < MARGIN_OF_ERROR;
}
Now I just came up with that way of determining the importance of the difference between two numbers. It might not be a very smart way to compute it, it might be appropriate to some situations and not to others. But the general idea is that you'll have to make a function that determines if two values are close enough with your own definition of "close".
Be aware though, JavaScript is one of the worst languages you can be doing math in. Integers become imprecise when they go beyond Number.MAX_SAFE_INT (which seems to be 9007199254740991 according to Chrome, not sure if it varies between browsers or if that's a standardized constant).
Update: If your target engine is es2020 or above, you can use the new BigInt javascript primitive, for numbers higher than Number.MAX_SAFE_INTEGER
BigInt(4.0329146112660565e+26) === BigInt(4.0329146112661e+26)
//false
See more information in MDN
var a = 4.0329146112660565e+26;
var b = 4.0329146112661e+26;
a = Math.round(a/10e+20)*10e+20
b = Math.round(b/10e+20)*10e+20
a == b;
I would suggest to use one of big numbers library:
big.js (https://www.npmjs.com/package/big.js)
Example:
var x = new Big('4.0329146112660565e+26');
var y = new Big('4.0329146112661e+26');
// Should print false
console.log('Comparision result' + x.eq(y));
big-numbers (https://www.npmjs.com/package/big-numbers)
Example:
var x = bn.of('4.0329146112660565e+26');
var y = bn.of('4.0329146112661e+26');
// Should print false
console.log('Comparision result' + x.equals(y));

Save integers as floats [duplicate]

This question already has answers here:
Save integer as float
(2 answers)
Closed 8 years ago.
function prec(numb){
var numb_string = numb.toString().split('.')
return numb_string[(numb_string.length - 1)].length
}
function randy(minimum, maximum) {
var most_accurate = Math.max ( prec(minimum), prec(maximum) );
return ( ( Math.random() * ( maximum - minimum ) + minimum ).toFixed( most_accurate ) );
}
// returns random numbers between these points. 1 decimal place of precision:
console.log( randy(2.4,4.4) );
// returns random numbers between these points. 3 decimal places of precision:
console.log( randy(2.443,4.445) );
// returns random numbers between these points. Want 3 decimal places of precision. However, get 0:
console.log( randy(2.000,4.000) );
// Why do I get 0 decimal places? Because floats are rounded into integers automatically:
console.log( 4.0 ); // want 4.0 to be logged. Instead I get '4'
You don't need to read how the functions work. Just the console logs.
Basically, I need to return a random number between two points to a degree of precision. The precision is automatically derived from the most precise float passed to the randy function.
This works fine when the number range is 3.5 3.7 or 34.4322 800.3233 but not 2.0, 3.0 or 4.0000, 5.0000
Then the number is appears to be automatically saved as an integer:
console.log( 2.0 ) //=> 2
I want to extend the Number prototype so that 2.0 is saved as 2.0 so that this function can find the precision:
function prec(numb){
var numb_string = numb.toString().split('.')
return numb_string[(numb_string.length - 1)].length
}
It currently thinks that 3.000000000 has a precision of 0 decimal places because if 3E8 is passed in as the numb parameter, it's read as 3. I want it read as 3.000000000
While I can do this randy(2.toFixed(3),3.toFixed(3)) it gets unreadable and it would be undeniably nicer to do this for smaller precisions: randy(2.000,3.000).
Is this possible?
Fiddle
There is only one number type in JS.
Aside from shortfalls of the type itself (causing headaches in other languages as well), it's a good thing.
If you want to display precision, then use num.toFixed(n); to store the number as a string, rounded to the precision you requested.
You can parse the string later in your code, operate on it, and then call .toFixed(n); on the result, to perpetuate the precision...
But unless you have specific needs, or are lumping several pieces of code together, are you not going to be concerned with rounding inaccuracies, versus just operating on full-precision values, and then rounding/formatting the end results?
Of course there are plenty of other solutions...
...keep track of the mandated precision with an int, representing the value... ...or keep an int representing the floating value as an int, based on preferred precision... 1.235 becomes [1, 235].
...anything is doable.
Subclassing, though, is really not going to be the answer.
you can define a class that helps you solve the problem especially with the toSting function
function NewNumber()
{
this.value = (typeof(arguments[0]) == "number") ? arguments[0] : 0;
this.decimal = (typeof(arguments[1]) == "number") ? arguments[1] : 0;
this.Val = function()
{
return parseFloat(this.value.toFixed(this.decimal));
}
this.toString = function()
{
return (this.value.toFixed(this.decimal)).toString();
}
}
Create a number like this
var Num = NewNumber(4.123545,3);
// first argument is the value
// and second one is decimal
To get the value of your variable, you should use the function Val like this
console.log(Num.Val()); // this one prints 4.123 on your console
Then the toString function
Num.toString() // it returns "4.123"
(new NewNumber(4,4)).toString(); // it returns "4.0000"
in your functions use the toString of the NewNumber class to solve your problem

Same periodic number is different for a if

I'm building a javascript-based web-app;
With a particular data input, a function returns a value of 10/3 = 3.333333333333333 (this is the amound of decimals shown by a colsole.log call); After about 200 lines of code, I have 2 variables (A and B) that contains that value, and I need to check if it is the same value;
The fact is, how is it possible to have an output like this?
console.log(A); //3.333333333333333
console.log(B); //3.333333333333333
console.log(A == B) //false
console.log(A-B == 0) //true??
I can imagine A == B is false due to how numbers are saved in the memory, but I wish it was a true; and what is really unexplainable to me is how comes the last line output is true?
console.log (or even toString) won't show you the full number down to the bit-by-bit difference. The floating point numbers used in JavaScript (and many other languages) are IEEE-754 double-precision floating point, and they're not perfectly precise, small discrepancies appear and can multiply.
Now, if you literally created A and B like this:
var A = 10 / 3;
var B = 10 / 3;
...then both comparisons would be true (proof). So apparently you're getting A one way, and B another, and the fact is that they are ever-so-slightly-different. (I'm quite surprised to hear A == B says false but A - B == 0 says true, though.)
You'll need to round them to the number of digits you think is appropriate, and compare the rounded result.

What is the Infinity property used for in Javascript?

Why is the Infinity property used as a command (rather than a result)
For example, this code below works, but the result isn't what I expected.
alert(isOdd(Infinity));
function isOdd(num) { return num%2==1; }
MDN REFERENCE
Infinity is a property of the global object, i.e. it is a variable in
global scope.
The initial value of Infinity is Number.POSITIVE_INFINITY. The value
Infinity (positive infinity) is greater than any other number. This
value behaves mathematically like infinity; for example, any positive
number multiplied by Infinity is Infinity, and anything divided by
Infinity is 0.
First what does this mean? In essence infinity is a concept not an actual value. Mathematics is based on concepts not values. For instance a number isn't a value, a numeral is.
The number 7 is the concept of the intended value, Romans wrote it as VII, in standard form (BASE-10) you write it as 7. In binary(BASE-2) you write it as 111. If you want to use a triangle or any other mark that is fine also as long as the concept is applied correctly.
Now that you know that, Infinity is simply the concept of being greater than any other number. It holds no value. The only reason that the basic concept of an infinity loops means to run forever is because in concept it means that whatever numeral iteration of that loop you are in (whether 1 or a million) infinity will always be greater than that number.
There are many methods to applying concepts in coding which is why everyone's code is ran differently but for example:
SAMPLE TAKEN FROM w3schools:
function findMax(x) {
var i;
var max = -Infinity;
for(i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
document.getElementById("demo").innerHTML = findMax(1, 123, 500, 115, 44, 88);
In the site's example they pass the argument of 6 values to the function findMax
findMax(1, 123, 500, 115, 44, 88);
They are then using a loop to stop at the parameters length. In the loop they are reassigning the max value from the concept of infinity to a value and if greater than that value when looped again the max value is then changed to the new high value.
Why is this important? Because in the example they use the concept of negative infinity which is simply the values of infinity decremented negatively. One could easily argue that 0 could replace -Infinity but they'd be wrong. This is why.
What if your value range is dependent upon negative values also being passed in the formula above? What if all you have is negative values that were dynamically captured from user input or another function?
Consider findMax was findMax(-1, -10, -15, -20);
0 would give a false output that it was the correct max value which wouldn't be what you wanted. You'd want -1 one to be the output. There are other methods to achieving the solution but for the sake of Infinity concept discussion I will end here.
I hope this sheds more light on the process of Infinity concept.
Infinity is a property of the global object that holds a numeric value representing the mathematical concept of infinity. I don't know any normal definition by which it could be called a "command."
With regard to your edit, that should return false (I ran it to confirm this suspicion, and it did on my browser). This is correct, as infinity is not normally considered an odd number.

Categories

Resources