Get the absolute value of a number in Javascript - javascript

I want to get the absolute value of a number in JavaScript. That is, drop the sign.
I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.
x = -25
x = x * x
x = Math.sqrt(x)
console.log(x)
Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?

You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.
var x = -25;
x = Math.abs(x); // x would now be 25
console.log(x);
Here are some test cases from the documentation:
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN

Here is a fast way to obtain the absolute value of a number. It's applicable on every language:
x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));

If you want to see how JavaScript implements this feature under the hood you can check out this post.
Blog Post
Here is the implementation based on the chromium source code.
function MathAbs(x) {
x = +x;
return (x > 0) ? x : 0 - x;
}
console.log(MathAbs(-25));

I think you are looking for Math.abs(x)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/abs

Alternative solution
Math.max(x,-x)
let abs = x => Math.max(x,-x);
console.log( abs(24), abs(-24) );
Also the Rick answer can be shorted to x>0 ? x : -x

to simply drop the sign of a number
var x = -25;
+`${x}`.replace('-', '');

Related

How to make an output Absolute Value in Javascript? [duplicate]

I want to get the absolute value of a number in JavaScript. That is, drop the sign.
I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.
x = -25
x = x * x
x = Math.sqrt(x)
console.log(x)
Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?
You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.
var x = -25;
x = Math.abs(x); // x would now be 25
console.log(x);
Here are some test cases from the documentation:
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
Here is a fast way to obtain the absolute value of a number. It's applicable on every language:
x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));
If you want to see how JavaScript implements this feature under the hood you can check out this post.
Blog Post
Here is the implementation based on the chromium source code.
function MathAbs(x) {
x = +x;
return (x > 0) ? x : 0 - x;
}
console.log(MathAbs(-25));
I think you are looking for Math.abs(x)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/abs
Alternative solution
Math.max(x,-x)
let abs = x => Math.max(x,-x);
console.log( abs(24), abs(-24) );
Also the Rick answer can be shorted to x>0 ? x : -x
to simply drop the sign of a number
var x = -25;
+`${x}`.replace('-', '');

How to access a constant nested function's parameter in javascript?

I was asked this question in an assessment I took and was not able to figure it out. Would like to know possible solutions.
Question:
Write one Javascript statement on the indicated line that will make the printed number always be between 10 and 20.
let x = 2;
let y = 8;
const a = function(b) {
return function(c) {
return x + y + Math.abs(b) + c;
};
};
// Statement will go here
const fn = a(x);
x = 4;
console.log(fn(Math.random() * 10));
I've tried assigning different values to variable y. But I think the culprit is to know what variable c would be in the nested function. Note that c would always be a number between 0 and 10 (as Math.random() is between 0 and 1, then multiplied by 10).
You already concluded correctly that the argument passed to fn is a random number between 0 and 10, which is c in the expression that the call to fn will evaluate: x + y + Math.abs(b) + c
So if fn must return a number between 10 and 20, then x + y + Math.abs(b) must equal 10.
We also see that the global variable x is set to 4 at a time that we cannot change it any more, but still before the call to fn, so that means y + Math.abs(b) must equal 6.
Now this gives us already a hint: as it stands, y is 8, which makes the conclusion in the previous paragraph impossible. So we must alter y. It is not yet too late, since the value of y will only be read when fn is called.
So what is Math.abs(b)? The local variable b is set when a is called. a is called with x, which at the time of that call is still 2. So Math.abs(b) is 2, and so we can derive that y must be 4.
One obvious way to make y to be 4 in one line:
y = 4;
(Alternatively, y-=4, y>>=1, y/=2, y^=12, ...etc)
If you want to provide a creative answer, try:
Math.random = function() { return 1.345; };

Javascript: is there a definite way to tell if the sum of two integers is greater than max int?

I am trying to write a test to check if the sum of two arbitrary integers is > 9007199254740992 or < -9007199254740992. Does js consistently behave in a way that is testable when this occurs?
According to MDN JavaScript uses double-precision floating-point format numbers as specified in IEEE 754.
So the actual safe bounds are max == Math.pow(2,53)-1 and min == -(Math.pow(2, 53)-1). These are encapsulated in the ECMAScript 6 Number class constants:
Number.MAX_SAFE_INTEGER; // == 9007199254740991
Number.MIN_SAFE_INTEGER; // == -9007199254740991
Taking these limits into account, here's a function that should meet your requirements to show when overflow or underflow can be expected under addition:
function additionWillOverflow(x,y) {
if( y > 0 ) {
return x > Number.MAX_SAFE_INTEGER - y;
}
return x < Number.MIN_SAFE_INTEGER - y;
}
And here are 2 illustrative test cases:
var x = 9007199254740990;
var y = 3;
console.log( additionWillOverflow(x,y) ); // true
console.log( x + y ); // 9007199254740992(!) - overflow
x = -9007199254740990;
y = -3;
console.log( additionWillOverflow(x,y) ); // true
console.log( x + y ); // -9007199254740992(!) - underflow
Due to the floating point representation mentioned above, starting at 2^53, javascript can only represent every second integer. From 2^54 js can only represent every fourth integer and so on. This behaviour should be consistent in any compliant implementation (haven't tested them all) and is the way floating point numbers work (check out wikipedia for more info).
Note that calling isNan(x+y) or isFinite(x+y) return false and true respectively for any numeric values even when they are outside the MAX_SAFE_INTEGER range (even when called on an incorrect numeric result).
Hope that helps.

Replace modulus by function

When I try to do 8067 % 80.67 I get 80.66999999999983, instead of 0 beacuse of known floating point javascript behaviour.
So I went and made a function for this, to avoid floating point javascript errors.
function math(a, b) {
var left = Math.abs(a),
times = 1,
abs = a >= 0 ? 1 : -1;
while (Math.abs(a) >= b * times) {
left -= b;
times++;
}
return (a - (b * (times - 1))) * abs;
}
http://jsfiddle.net/s5w3C/
So my question is: is this usefull, ie a good tool to use instead of %? is there cases where this will also give falsy results like the modulus % oprator.
I am looking for a tools to calculate % consistently.
I didn't really inspect the algorithm for correctness, but if you care about efficiency, this is a bad idea. Basically, the larger the input, the slower your code will execute.
I think any fix will only work to a certain level of accuracy and for certain sized numbers. Perhaps something like the following will be sufficient:
function nearlyMod(a, b) {
var precision = ('' + b).split('.').length;
var estimate = (a % b).toFixed(precision);
return estimate == b ? 0 : +estimate;
}
console.log(nearlyMod(8067, 80.66)); // 1
console.log(nearlyMod(8067, 80.67)); // 0
console.log(nearlyMod(8067, 80.68)); // 79.68
It tests if the result is an even divisor within the precision of the original number. If so, it returns 0, otherwise it returns a number to the same precision (which may or may not be what you want).
The result is always a number (the value returned from toFixed is a string, hence +estimate).
A better name might be "roundedMod" or similar.

Javascript - Find the base of an exponential equation

I was wondering if anyone knew how to find the base of an exponential equation in Javascript.
I couldn't find any function that allows this to be done (e.g. using the Math functions).
For example, how do I find 'b' in the following equation:
y = b^t
Thanks in advance for any help you can provide.
If you know what are the values of y and t are, you can get the value of b by calculating the t-th root of y like this:
Math.pow(y, 1/t);
Source:
JavaScript: Calculate the nth root of a number
What you need is math and the logarithm.
y = b^t
=> t = log(y) / log(b)
=> log(b) = log(y) / t
=> b = 10 ^ ( log(y) / t )
So it would be something like
b = Math.pow(10, (Math.log(y) / t));
-Hannes

Categories