Home > Mobile >  python and calculating the power of a number
python and calculating the power of a number

Time:11-10

I was asked to calculate the cubed root of a number in python3 and used the following code:

import numpy as np          # numerical routines
def myfunct(x):
    return np.power(x,3./2.)

xStar = 4
print('Exact value at',xStar,' is in myfunc ',myfunct(xStar))

This is fine, however by accident I found the following works

import numpy as np          # numerical routines
def myfunct(x):
    return np.power(x,3./2.)

def anotherfunct(x):
    return pow(x,3./2.)

xStar = 4
print('value at',xStar,' is in myfunc',myfunct(xStar))
print('value at',xStar,' is in anotherfunc',anotherfunct(xStar))

N = 3
xpt = np.linspace( 8., 12., num=N )
print(xpt)
print(myfunct(xpt))
print(wrongfunct(xpt))

that seems to give the same answer, namely

[ 8.   9.5 11. ]
[22.627417   29.28096651 36.48287269]
[22.627417   29.28096651 36.48287269]

My question is, is pow() really the same as np.power() and, if so, would it be considered bad programming practice to use pow() over np.power() in numerical programming?

CodePudding user response:

prehaps take a look at the documentation for both:

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply.

Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape.

the main difference - as with most of the numpy functions compared to built in ones - is only relevant when you look at the types of values input. If you only expect to use single value inputs (calculate it for a single number only) then they will act identically, if you want to do the calculation for an array of inputs at once the built in pow won't be happy with that.

  • Related