Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculation error with pow operator

Tags:

python

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?

like image 897
casso Avatar asked May 20 '14 11:05

casso


People also ask

Can pow () take 3 arguments?

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.

What is pow () function?

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.

How does POW function work in C?

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.

Does math POW return a float?

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.


1 Answers

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
like image 196
vaultah Avatar answered Oct 05 '22 03:10

vaultah