console.log(Math.pow(9, 1 / 2) === 9 ** 1 / 2) // false
console.log(9 ** 1 / 2) // 4.5
Asked
Active
Viewed 80 times
-1
-
10Because you want `9 ** (1/2)`, but are doing `(9 ** 1)/2`. Exponentiation has higher operator precedence than division. – Bergi Jun 11 '22 at 16:57
-
4.5 is the correct result, if you don't use any parenthesis, to change the precedence. – The Fool Jun 11 '22 at 16:59
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – dotsinspace Jun 11 '22 at 17:00
-
You are calculating `Math.pow(9,1) / 2` which is the same as `9/2` – slebetman Jun 11 '22 at 17:00
-
Correctly, you'd use decimals (0.5) to avoid issues like this. – roberrrt-s Jun 11 '22 at 17:00
1 Answers
0
It's because of operator precedence. **
has a higher precedence than /
in the same way that *
has higher precedence thatn +
.
You wouldn't expect 3 * 3 + 2
to equal 15 do you?
So similarly your 9**1 / 2
is interpreted as (9**1) / 2
. If you mean to raise 9
to the power of 0.5
you need to clarify it as:
9 ** (1/2)

slebetman
- 109,858
- 19
- 140
- 171
-
Or, alternatively, you can write this as `9 ** 0.5`, which doesn't run into order-of-operations issues. – CerebralFart Jun 11 '22 at 17:09
-
Interestingly enough, this is something that people might struggle with, even if you do math with pen and paper. `2x^2 != (2x)^2` – Swiffy Jun 11 '22 at 17:12
-
@CerebralFart That is a neat trick but doesn't help you in real code because in real code you usually have to deal with variables like `1/x` which can't be hardcoded. Teach someone about order of operations and the use of braces and it will solve all his future problems – slebetman Jun 11 '22 at 17:14