6

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.

marco
  • 915
  • 4
  • 17
  • 35

2 Answers2

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

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

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.

Astrophe
  • 568
  • 1
  • 7
  • 25