views:

154

answers:

4

Hello,

I found this code in a web page for calculating the BMI (Body mass index), which value is: Weight/Height * Height, the result on the web page is obviously wrong so looking at the code I´ve found this operator.

I supose they wanted to calculate the square of the height but this is not happening.

The web page is: http://www.loreal-paris.es/articulos/calcular-indice-masa-corporal.aspx

<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>
+3  A: 

This is the bitwise XOR operator.

Petar Minchev
+7  A: 

The ^ operator is the bitwise XOR operator. To square a value, use Math.pow:

var altura2 = Math.pow($('#ddl_altura').attr("value")/100, 2);
Gumbo
in a language like Javascript where types are so loose they barely exist, i'm almost surprised there are even bitwise operations :)
tenfour
I know the pow function (the Loreal Web Master seems no...) but I couldn´t find the ^ operator for javascript. Thanks for the link!
Torres
Nice catch! Forwarded it to my spanish friend, who got a little shocked. Noticed how for example 200cm/70kg gives you a BMI of infinity ;-)
Michael
Haha, that´s the same test I did!! now I know the answer, I feel better. I was scared for having a BMI of infinity...
Torres
To square a value, multiply it by itself. It's faster and more accurate on almost all platforms.
Stephen Canon
+1  A: 

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

Sarfraz
+2  A: 

^ 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 but for square you better use x*x as Math.pow uses logarithms and you get more approximations errors. ( x² ~ exp(2.log(x)) )

ring0
Wasn't aware of the logarithm fact! Thanks! (It's thus probably also faster, isn't it?)
Michael
Likely to be faster (while math processors are pretty fast for `double` simple operations - log is likely to be slower, while using an optimization of the Taylor series).
ring0