python numpy.power()數組元素求n次方案例
如下所示:
numpy.power(x1, x2)
數組的元素分別求n次方。x2可以是數字,也可以是數組,但是x1和x2的列數要相同。
>>> x1 = range(6) >>> x1 [0, 1, 2, 3, 4, 5] >>> np.power(x1, 3) array([ 0, 1, 8, 27, 64, 125])
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.power(x1, x2) array([ 0., 1., 8., 27., 16., 5.])
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
補充:python求n次方的函數_python實現pow函數(求n次冪,求n次方)
類型一:求n次冪
實現 pow(x, n),即計算 x 的 n 次冪函數。其中n為整數。pow函數的實現——leetcode
解法1:暴力法
不是常規(guī)意義上的暴力,過程中通過動態(tài)調整底數的大小來加快求解。代碼如下:
class Solution: def myPow(self, x: float, n: int) -> float: judge = True if n<0: n = -n judge = False if n==0: return 1 final = 1 # 記錄當前的乘積值 tmp = x # 記錄當前的因子 count = 1 # 記錄當前的因子是底數的多少倍 while n>0: if n>=count: final *= tmp tmp = tmp*x n -= count count +=1 else: tmp /= x count -= 1 return final if judge else 1/final
解法2:根據奇偶冪分類(遞歸法,迭代法,位運算法)
如果n為偶數,則pow(x,n) = pow(x^2, n/2);
如果n為奇數,則pow(x,n) = x*pow(x, n-1)。
遞歸代碼實現如下:
class Solution: def myPow(self, x: float, n: int) -> float: if n<0: n = -n return 1/self.help_(x,n) return self.help_(x,n) def help_(self,x,n): if n==0: return 1 if n%2 == 0: #如果是偶數 return self.help_(x*x, n//2) # 如果是奇數 return self.help_(x*x,(n-1)//2)*x
迭代代碼如下:
class Solution: def myPow(self, x: float, n: int) -> float: judge = True if n < 0: n = -n judge = False final = 1 while n>0: if n%2 == 0: x *=x n //= 2 final *= x n -= 1 return final if judge else 1/final
python位運算符簡介
其實跟上面的方法類似,只是通過位運算符判斷奇偶性并且進行除以2的操作(移位操作)。代碼如下:
class Solution: def myPow(self, x: float, n: int) -> float: judge = True if n < 0: n = -n judge = False final = 1 while n>0: if n & 1: #代表是奇數 final *= x x *= x n >>= 1 # 右移一位 return final if judge else 1/final
類型二:求n次方
實現 pow(x, n),即計算 x 的 n 次冪函數。其中x大于0,n為大于1整數。
解法:二分法求開方
思路就是逐步逼近目標值。以x大于1為例:
設定結果范圍為[low, high],其中l(wèi)ow=0, high = x,且假定結果為r=(low+high)/2;
如果r的n次方大于x,則說明r取大了,重新定義low不變,high= r,r=(low+high)/2;
如果r的n次方小于x,則說明r取小了,重新定義low=r,high不變,r=(low+high)/2;
代碼如下:
class Solution: def myPow(self, x: float, n: int) -> float: # x為大于0的數,因為負數無法開平方(不考慮復數情況) if x>1: low,high = 0,x else: low,high =x,1 while True: r = (low+high)/2 judge = 1 for i in range(n): judge *= r if x >1 and judge>x:break # 對于大于1的數,如果當前值已經大于它本身,則無需再算下去 if x <1 and judge if abs(judge-x)<0.0000001: # 判斷是否達到精度要求 print(pow(x,1/n)) # pow函數計算結果 return r else: if judge>x: high = r else: low = r
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
Python實戰(zhàn)快速上手BeautifulSoup庫爬取專欄標題和地址
BeautifulSoup是爬蟲必學的技能,BeautifulSoup最主要的功能是從網頁抓取數據,Beautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼2021-10-10
Pycharm創(chuàng)建項目時如何自動添加頭部信息
這篇文章主要介紹了Pycharm創(chuàng)建項目時 自動添加頭部信息,需要的朋友可以參考下2019-11-11

