I have some JavaScript code:
<script type="text/javascript">
$(document).ready(function(){
$('#calcular').click(function() {
var altura2 = ((($('#ddl_altura').attr("value"))/100)^2);
var peso = $('#ddl_peso').attr("value");
var resultado = Math.round(parseFloat(peso / altura2)*100)/100;
if (resultado > 0) {
$('#resultado').html(resultado);
$('#imc').show();
};
});
});
</script>
What does the ^ (caret) symbol mean in JavaScript?
The ^ operator is the bitwise XOR operator. To square a value, use Math.pow:
var altura2 = Math.pow($('#ddl_altura').attr("value")/100, 2);
^ is performing exclusive OR (XOR), for instance
6 is 110 in binary, 3 is 011 in binary, and
6 ^ 3, meaning 110 XOR 011 gives 101 (5).
110 since 0 ^ 0 => 0
011 0 ^ 1 => 1
--- 1 ^ 0 => 1
101 1 ^ 1 => 0
Math.pow(x,2) calculates x² but for square you better use x*x as Math.pow uses logarithms and you get more approximations errors. ( x² ~ exp(2.log(x)) )
Its called bitwise XOR. Let me explain it:
You have :
Decimal Binary
0 0
1 01
2 10
3 11
Now we want 3^2= ?
then we have 11^10=?
11
10
---
01
---
so 11^10=01
01 in Decimal is 1.
So we can say that 3^2=1;
This is the bitwise XOR operator.
The bitwise XOR operator is indicated
by a caret ( ^ ) and, of course, works
directly on the binary form of
numbers. Bitwise XOR is different from
bitwise OR in that it returns 1 only
when exactly one bit has a value of 1.
Source: http://www.java-samples.com/showtutorial.php?tutorialid=820
Related
I was doing this question in leetcode.
Request:
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
I can't understand the solution it gave
Could someone explain how this getSum function works?
Here is the answer in JS:
var getSum=function(a,b) {
const Sum = a^b; //I can't understand how those two line's code can
const carry = (a & b) << 1; //get the sum
if(!carry) {
return Sum
}
return getSum(Sum,carry);
};
console.log(getSum(5,1));
It's basically replicating the half-adder
Adding 2 bits A and B produces 2 outputs: a sum and a carry bit like below
╔═══════╤═════════════╗
║ Input │ Output ║
╠═══╤═══╪═══════╤═════╣
║ A │ B │ carry │ sum ║
╟───┼───┼───────┼─────╢
║ 0 │ 0 │ 0 │ 0 ║
╟───┼───┼───────┼─────╢
║ 1 │ 0 │ 0 │ 1 ║
╟───┼───┼───────┼─────╢
║ 0 │ 1 │ 0 │ 1 ║
╟───┼───┼───────┼─────╢
║ 1 │ 1 │ 1 │ 0 ║
╚═══╧═══╧═══════╧═════╝
From the table we get the logic for the outputs: carry = A and B, sum = A xor B
XOR is also called a carry-less add operator, and represented by ⊕ with the + symbol inside
So the snippet above is working like this
const Sum=a^b; // sum = a xor b = a ⊕ b
const carry=(a&b)<<1; // carry = 2*(a and b), since we carry to the next bit
if(!carry){
return Sum; // no carry, so sum + carry = sum
}
return getSum(Sum,carry); // a + b = sum + carry
So a^b adds each bit in a and b simultaneously, leaving the non-carry sum of a and b in Sum. Then we have to add carry to the carry-less sum to get the final result, since we have only a half-adder instead of a full-adder which does a + b = a ⊕ b + carry
See also
Adding two numbers without + operator (Clarification)
What is the best way to add two numbers without using the + operator?
adds two numbers without using + or any arithmetic operators
Adding two numbers without using the addition operator
Let's learn by example. Imagine that a = 3 and b = 5
In binary notation they are a = 0011 and b = 0101
XOR:
a^b is XOR operator. When compare two bits it returns 0 if they are same and 1 if they are different. 01^10 => 11
So when we're doing a^b result will be 0110.
AND + SHIFT
a&b performs logical AND operation. It returns 1 only when a = b = 1.
In our case the result is 0001
<< shifts it(adds 0 on the right side) and result became 0010 which sets carry variable true. (only 0000 will be false).
Next iterations:
Everything repeats but now a = 0110 and b = 0010 (Sum and carry from last execution)
Now a^b = 0100 and (a&b)<<1 = 0100
Repeating again.
Now a^b = 0000 and (a&b)<<1 = 1000
And again.
Now a^b = 1000 and (a&b)<<1 = 0000. Now carry is finally false. And we're returning 1000 which is decimal 8.
Everything worked fine since 3+5=8
int result = p ^ q; // XOR Operator, + without carry 0+0=0, 0+1=1+0=1, 1+1=0
int carry = (p & q) << 1; // Left Shift, 1+1=2
if (carry != 0) {
return getSum(result, carry);
}
return result;
Start By p=5,q=6. Then the XOR would be,
0101
0110
------
0011
So, XORing results in (0011) which is actually 3 in decimal. Then ANDing p and q we get,
0101
0110
-------
0100
We get 4 (100 in binary) by ANDing 5 & 6, now if we left shift this value by 1, we get
0100<<1=1000
So we get 8 (1000 in binary) after first recursion.As the result (carry variable) isnt zero, lets recursion again by xor value and carry value.
getSum(3, 8);
So, doing the first XORing we get,
0011
1000
-------
1011
The XORing this time yielded in 11 (1011 binary),so we perform the AND now,
0011
1000
-------
0000
We get all ZERO for ANDing 3 and 8, so this time the left shift operator also results in ZERO, as we have no 1 here which may give us a value by left shifing zeroes.
As the carry variable is now Zero, we come to the end of recursion and the XORed value will be the Sum, which is 11 (1011 in Binary).
Hope you get the working of the procedure. You can learn more by learning bitwise operation, as its the way the machine do the arithmatic operations.
^ is XOR, a bitwise operation. On a single bit, the rules are 0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 0 = 0, and 1 ^ 1 = 0, and you simply extend perform it on corresponding bits when dealing with multi-bit values. The name is short for "exclusive or", and comes from the fact that A ^ B is 1 if and only if either A or B is 1, not both. But, it's more interesting to talk about its other name, ⊕. ⊕ is + but slightly different. You'll notice that the rules for ⊕ are similar to the rules for addition: 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1, and 1 + 1 = 10. ⊕ is +, except 1 ⊕ 1 = 0; that is, ⊕ is +, except without carrying. This holds for multiple bits: 011 + 001 = 100, because you carry a 1 out of the ones place into the twos place, and then carry a 1 again into the fours place. Then, 011 ⊕ 001 = 010, because you just don't carry.
Now, when doing real addition, when do you carry? In binary, the answer is very simple: you carry a 1 into the next place when there are two 1s in a given place. This is easily understood as a bitwise AND, &. 1 & 1 = 1, and 0 otherwise. For 011 + 001, addition without carrying gives 011 ⊕ 001 = 010, and we can tell we need to carry a 1 out of the ones place because 011 & 001 = 001. The shifting in (a & b) << 1 turns a number "where do I need to carry from?" into "where do I need to add carries?": (011 & 001) << 1 = 010; I need to add a carry bit in the twos place.
So, in getSum, we want to know a + b. We compute the addition without carrying with a ^ b, and we find where we need to add carry bits with (a & b) << 1. Now, we just need to add those two together. Well, we already have a function for adding numbers together; it's called getSum. So, we basically just write function getSum(a, b) { return getSum(a ^ b, (a & b) << 1); }, except we make sure to short-circuit if there is nothing to carry, saving us from infinite recursion.
This question already has answers here:
find the only unpaired element in the array
(10 answers)
What are bitwise operators?
(9 answers)
What do these JavaScript bitwise operators do?
(3 answers)
Closed 5 years ago.
Saw an interesting piece of code to find a lonely number in a list of duplicate numbers (where every number in the list occurs twice except for one).
function findNonPaired(listOfNumbers) {
let nonPairedNumber = 0
listOfNumbers.forEach((n) => {
nonPairedNumber ^= n
})
return nonPairedNumber
}
const x = [1,5,4,3,9,2,3,1,4,5,9]
console.log(findNonPaired(x))
This solution looks very elegant, but I'm curious at to what the ^= operator is actually doing here?
a ^= b is the same as a = a ^ b where ^ is the bitwise XOR operator.
0 ^ 0 === 0
1 ^ 0 === 1
0 ^ 1 === 1
1 ^ 1 === 0
This is a neat algorithm. Let's trace one execution with the list [8, 12, 8] for example:
0 ^ 8 = 0000 ^ 1000 = 1000
1000 ^ 1100 = 0100
0100 ^ 1000 = 1100 = 12
The word "duplicate" isn't correct. This algorithm tests for parity. A simple but somewhat wrong definition is "when everything has a pair". pair...parity.
[2,2,2,3,3,5,5,5,5] will return 2 because everything else has a pair.
[3,4,5] will actually return 2 (011^100^101 -> 010) because that is the xor of all the unpaired items.
Like other answers say - it is a bitwise XOR.
About the algorythm - it is cool if you are sure that the duplicates are even count. When a number is XOR-ed with x and later again XOR-ed with x it will return to it's previuos value. If one number is seen 3 times in this chain, the 3-rd occurence will fool this algorythm.
Also if there is one more value that is single in the chain, like:
a, b, c, X, a, c, b, Y
the result will be (X ^ Y) and you can't be sure if you have one unique value or more.
I do my calculations like this:
117^196
I get:
177
Now what I want to do is to get 117 back so I need to make a replace
(replace)^196 = 117
Whats the opposite operation from the xor operator?
The opposite of xor is xor :). If you xor something twice (a^b)^b == a.
This is relatively easy to show. For each bit:
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
Doing this on any pair of numbers a,b, it's easy to see that
a^b xor'd by either a or b yields the other (xor a yields b, and vice versa)
1 2 filter result
0^0^0 = 0
0^1^0 = 1
0^1^1 = 0
1^0^0 = 1
1^0^1 = 0
1^1^1 = 1
it's just xor it self.
like +'s opposite is -
xor's opposite is xor
Just use the result that you got: 177
117 ^ 196 = 177 | () ^ 196
117 ^ 196 ^ 196 = 177 ^ 196 | self-inverse
117 ^ 0 = 177 ^ 196 | neutral element
117 = 177 ^ 196
XOR has three important properties. It is
associative
commutative
self-inverse
This means that a value is its own inverse:
a^a = 0
Since it is also both commutative and associative, you can rearrange and xor-expression containing an event amount of the same operands like this:
a^O^b^c^O^d = O^O^a^b^c^d = 0^a^b^c^d = a^b^c^d
You could say that operands that appear an even amount of time "cancel each other out".
Are there any side effects if i convert a string to a number like below..
var numb=str*1;
If I check with the below code it says this is a number..
var str="123";
str=str*1;
if(!isNaN(str))
{
alert('Hello');
}
Please let me know if there are any concerns in using this method..
When you use parseFloat, or parseInt, the conversion is less strict. 1b5 -> 1.
Using 1*number or +number to convert will result in NaN when the input is not valid number. Though unlike parseInt, floating point numbers will be parsed correctly.
Table covering all possible relevant options.
//Variables // parseInt parseFloat + 1* /1 ~~ |0 ^1 >>0 >>>0
var a = '123,',// 123 123 NaN 0 & <<0 0
b = '1.e3',// 1 1000 1000 1000 1000
c = '1.21',// 1 1.21 1.21 1 1
d = '0020',// 16 20 20 20 20
e = '0x10',// 16 0 16 16 16
f = '3e9', // 3 3000000000 <-- -1294967296 3000000000
g = '3e10',// 3 30000000000 <-- -64771072 4230196224
h = 3e25 ,// 3 3e+25 3e+25 0 0
i = '3e25',// 3 3e+25 3e+25 0 0
j = 'a123',// NaN NaN NaN 0 0
k = ' 1 ',// 1 1 1 1 1
l = ' ',// NaN NaN 0 0 0
m = '.1 ',// NaN 0.1 0.1 1 1
n = '1. ',// 1 1 1 1 1
o = '1e999',// 1 Infinity Infinity 0 0
p = '1e-999',// 1 0 0 0 0
q = false ,// NaN NaN 0 0 0
r = void 0,// NaN NaN NaN 0 0
_ = function(){return 1;}, /* Function _ used below */
s={valueOf:_},//NaN NaN 1 1 1
t={toString:_};// 1 1 1 1 1
// Intervals: (-1e+20, +1e20) (-∞,+∞) (-∞,+∞) (-2³¹,+2³¹) [0, 2³²)
// In FF9 and Chrome 17, Infinity === Math.pow(2, 1024), approx. 1.7976e+308
// In FF9 and Chrome 17, bitwise operators always return 0 after about ±1e+25
Notes on number conversion methods:
The number conversion always fail if the first character, after trimming white-space, is not a number.
parseInt returns an integer representation of the first argument. When the radix (second argument) is omitted, the radix depends on the given input.
0_ = octal (base-8), 0x_ = hexadecimal (base-16). Default: base-10.
parseInt ignores any non-digit characters, even if the argument was actually a number: See h, i.
To avoid unexpected results, always specify the radix, usually 10: parseInt(number, 10).
parseFloat is the most tolerant converter. It always interpret input as base-10, regardless of the prefix (unlike parseInt). For the exact parsing rules, see here.
The following methods will always fail to return a meaningful value if the string contains any non-number characters. (valid examples: 1.e+0 .1e-1)
+n, 1*n, n*1, n/1 and Number(n) are equivalent.
~~n, 0|n, n|0, n^1, 1^n, n&n, n<<0 and n>>0 are equivalent. These are signed bitwise operations, and will always return a numeric value (zero instead of NaN).
n>>>0 is also a bitwise operation, but does not reserve a sign bit. Consequently, only positive numbers can be represented, and the upper bound is 232 instead of 231.
When passed an object, parseFloat and parseInt will only look at the .toString() method. The other methods first look for .valueOf(), then .toString(). See q - t.
NaN, "Not A Number":typeof NaN === 'number'
NaN !== NaN. Because of this awkwardness, use isNaN() to check whether a value is NaN.
When to use which method?
parseFloat( x ) when you want to get as much numeric results as possible (for a given string).
parseFloat( (x+'').replace(/^[^0-9.-]+/,'') ) when you want even more numeric results.
parseInt( x, 10 ) if you want to get integers.
+x, 1*x .. if you're only concerned about getting true numeric values of a object, rejecting any invalid numbers (as NaN).
~~, 0| .. if you want to always get a numeric result (zero for invalid).
>>>0 if negative numbers do not exists.
The last two methods have a limited range. Have a look at the footer of the table.
The shortest way to test whether a given parameter is a real number is explained at this answer:
function isNumber(n) {
return typeof n == 'number' && !isNaN(n - n);
}
I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would give back the same value, wouldn't it?
It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number.
In other words, it yields:
function(x) {
if(x < 0) return Math.ceil(x);
else return Math.floor(x);
}
only if x is between -(231) and 231 - 1. Otherwise, overflow will occur and the number will "wrap around".
This may be considered useful to convert a function's string argument to a number, but both because of the possibility of overflow and that it is incorrect for use with non-integers, I would not use it that way except for "code golf" (i.e. pointlessly trimming bytes off the source code of your program at the expense of readability and robustness). I would use +x or Number(x) instead.
How this is the NOT of the NOT
The number -43.2, for example is:
-43.210 = 111111111111111111111111110101012
as a signed (two's complement) 32-bit binary number. (JavaScript ignores what is after the decimal point.) Inverting the bits gives:
NOT -4310 = 000000000000000000000000001010102 = 4210
Inverting again gives:
NOT 4210 = 111111111111111111111111110101012 = -4310
This differs from Math.floor(-43.2) in that negative numbers are rounded toward zero, not away from it. (The floor function, which would equal -44, always rounds down to the next lower integer, regardless of whether the number is positive or negative.)
The first ~ operator forces the operand to an integer (possibly after coercing the value to a string or a boolean), then inverts the lowest 31 bits. Officially ECMAScript numbers are all floating-point, but some numbers are implemented as 31-bit integers in the SpiderMonkey engine.
You can use it to turn a 1-element array into an integer. Floating-points are converted according to the C rule, ie. truncation of the fractional part.
The second ~ operator then inverts the bits back, so you know that you will have an integer. This is not the same as coercing a value to boolean in a condition statement, because an empty object {} evaluates to true, whereas ~~{} evaluates to false.
js>~~"yes"
0
js>~~3
3
js>~~"yes"
0
js>~~false
0
js>~~""
0
js>~~true
1
js>~~"3"
3
js>~~{}
0
js>~~{a:2}
0
js>~~[2]
2
js>~~[2,3]
0
js>~~{toString: function() {return 4}}
4
js>~~NaN
0
js>~~[4.5]
4
js>~~5.6
5
js>~~-5.6
-5
In ECMAScript 6, the equivalent of ~~ is Math.trunc:
Returns the integral part of a number by removing any fractional digits. It does not round any numbers.
Math.trunc(13.37) // 13
Math.trunc(42.84) // 42
Math.trunc(0.123) // 0
Math.trunc(-0.123) // -0
Math.trunc("-1.123")// -1
Math.trunc(NaN) // NaN
Math.trunc("foo") // NaN
Math.trunc() // NaN
The polyfill:
function trunc(x) {
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
The ~ seems to do -(N+1). So ~2 == -(2 + 1) == -3 If you do it again on -3 it turns it back: ~-3 == -(-3 + 1) == 2 It probably just converts a string to a number in a round-about way.
See this thread: http://www.sitepoint.com/forums/showthread.php?t=663275
Also, more detailed info is available here: http://dreaminginjavascript.wordpress.com/2008/07/04/28/
Given ~N is -(N+1), ~~N is then -(-(N+1) + 1). Which, evidently, leads to a neat trick.
Just a bit of a warning. The other answers here got me into some trouble.
The intent is to remove anything after the decimal point of a floating point number, but it has some corner cases that make it a bug hazard. I'd recommend avoiding ~~.
First, ~~ doesn't work on very large numbers.
~~1000000000000 == -727279968
As an alternative, use Math.trunc() (as Gajus mentioned, Math.trunc() returns the integer part of a floating point number but is only available in ECMAScript 6 compliant JavaScript). You can always make your own Math.trunc() for non-ECMAScript-6 environments by doing this:
if(!Math.trunc){
Math.trunc = function(value){
return Math.sign(value) * Math.floor(Math.abs(value));
}
}
I wrote a blog post on this for reference: http://bitlords.blogspot.com/2016/08/the-double-tilde-x-technique-in.html
Converting Strings to Numbers
console.log(~~-1); // -1
console.log(~~0); // 0
console.log(~~1); // 1
console.log(~~"-1"); // -1
console.log(~~"0"); // 0
console.log(~~"1"); // 1
console.log(~~true); // 1
console.log(~~false); // 0
~-1 is 0
if (~someStr.indexOf("a")) {
// Found it
} else {
// Not Found
}
source
~~ can be used as a shorthand for Math.trunc()
~~8.29 // output 8
Math.trunc(8.29) // output 8
Here is an example of how this operator can be used efficiently, where it makes sense to use it:
leftOffset = -(~~$('html').css('padding-left').replace('px', '') + ~~$('body').css('margin-left').replace('px', '')),
Source:
See section Interacting with points
Tilde(~) has an algorihm -(N+1)
For examle:
~0 = -(0+1) = -1
~5 = -(5+1) = -6
~-7 = -(-7+1) = 6
Double tilde is -(-(N+1)+1)
For example:
~~5 = -(-(5+1)+1) = 5
~~-3 = -(-(-3+1)+1) = -3
Triple tilde is -(-(-(N+1)+1)+1)
For example:
~~~2 = -(-(-(2+1)+1)+1) = -3
~~~3 = -(-(-(3+1)+1)+1) = -4
Same as Math.abs(Math.trunc(-0.123)) if you want to make sure the - is also removed.
In addition to truncating real numbers, ~~ can also be used as an operator for updating counters in an object. The ~~ applied to an undefined object property will resolve to zero, and will resolve to the same integer if that counter property already exists, which you then increment.
let words=["abc", "a", "b", "b", "bc", "a", "b"];
let wordCounts={};
words.forEach( word => wordCounts[word] = ~~wordCounts[word] + 1 );
console.log("b count == " + wordCounts["b"]); // 3
The following two assignments are equivalent.
wordCounts[word] = (wordCounts[word] ? wordCounts[word] : 0) + 1;
wordCounts[word] = ~~wordCounts[word] + 1;