Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I calc pow of fractions or nth root square in numpy?

I'm trying to calculate the 8th root square of a value or its ^1/8, but numpy is always returning the wrong value

temp = 141.18
h2 = temp ** (1/8)
h2_ = np.power(temp, (1/8))

my output is always 1.0 . I've tried square command too. I need to use numpy, I'm using other numpy arrays in mycode, just to keep compatible.

like image 334
marco Avatar asked Oct 21 '14 15:10

marco


People also ask

How do you write the fourth root in Python?

The n -th root of x is x^(1/n) , so 20736 ** (1.0/4) . Hint: n^(1/4) = (n^(1/2))^(1/2) .


2 Answers

>>> 1/8
0
>>> 1./8
0.125

And of course, anything to the power of 0 results in 1.

like image 122
Ignacio Vazquez-Abrams Avatar answered Dec 31 '22 07:12

Ignacio Vazquez-Abrams


Understand the numeric tower.

Rule 1: Given two operands of the same type, the result will have that type.

e.g. int / int = int

temp**(1/8) does not give the 8th root of temp because:

>>>1/8
0

Rule 2: If the operands are mixed, one of them will be coerced up the numeric tower: integer --> rational --> float --> complex.

e.g. float / int = float

>>>1./8 # 1. is a float 
0.125

Note: There may be cases where these rules do not apply to true division / and floor division // but I don't fully understand them. See the link.

"They've done studies you know. It works 60% of the time... everytime." - Brian Fantana

Trap: In the OPs question the expression temp**(1/8) is made of mixed operands (temp is a float) so why isn't (1/8) a float?

The operands are evaluated according to BODMAS/BIDMAS so (1/8) is evaluated first, the resulting expression becomes temp**0 and at this point 0 is coerced to a float.

Any positive int or float to the power 0.0 is 1.0.

like image 23
Astrophe Avatar answered Dec 31 '22 08:12

Astrophe