What should print (-2 ** 2)
return? According to my calculations it should be 4
, but interpreter returns -4
.
Is this Python's thing or my math is that terrible?
The pow() method takes three parameters: number - the base value that is raised to a certain power. power - the exponent value that raises number. modulus - (optional) divides the result of number paused to a power and finds the remainder: number^power % modulus.
The pow() function computes the power of a number. The pow() function takes two arguments (base value and power value) and, returns the power raised to the base number. For example, [Mathematics] xy = pow(x, y) [In programming] The pow() function is defined in math. h header file.
Given two numbers base and exponent, pow() function finds x raised to the power of y i.e. xy. Basically in C exponent value is calculated using the pow() function. pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function.
pow() function is that the math function will always convert both numbers to a float. Because of this, the result of the function will always be a float.
According to docs, **
has higher precedence than -
, thus your code is equivalent to -(2 ** 2)
. To get the desired result you could put -2
into parentheses
>>> (-2) ** 2
4
or use built-in pow
function
>>> pow(-2, 2)
4
or math.pow
function (returning float
value)
>>> import math
>>> math.pow(-2, 2)
4.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With