python numpy.power()數(shù)組元素求n次方案例
numpy.power(x1, x2)
數(shù)組的元素分別求n次方。x2可以是數(shù)字,也可以是數(shù)組,但是x1和x2的列數(shù)要相同。
>>> 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次方的函數(shù)_python實現(xiàn)pow函數(shù)(求n次冪,求n次方)
類型一:求n次冪實現(xiàn) pow(x, n),即計算 x 的 n 次冪函數(shù)。其中n為整數(shù)。pow函數(shù)的實現(xiàn)——leetcode
解法1:暴力法不是常規(guī)意義上的暴力,過程中通過動態(tài)調(diào)整底數(shù)的大小來加快求解。代碼如下:
class Solution:def myPow(self, x: float, n: int) -> float:judge = Trueif n<0:n = -njudge = Falseif n==0:return 1final = 1 # 記錄當前的乘積值tmp = x # 記錄當前的因子count = 1 # 記錄當前的因子是底數(shù)的多少倍while n>0:if n>=count:final *= tmptmp = tmp*xn -= countcount +=1else:tmp /= xcount -= 1return final if judge else 1/final解法2:根據(jù)奇偶冪分類(遞歸法,迭代法,位運算法)
如果n為偶數(shù),則pow(x,n) = pow(x^2, n/2);
如果n為奇數(shù),則pow(x,n) = x*pow(x, n-1)。
遞歸代碼實現(xiàn)如下:
class Solution:def myPow(self, x: float, n: int) -> float:if n<0:n = -nreturn 1/self.help_(x,n)return self.help_(x,n)def help_(self,x,n):if n==0:return 1if n%2 == 0: #如果是偶數(shù)return self.help_(x*x, n//2)# 如果是奇數(shù)return self.help_(x*x,(n-1)//2)*x
迭代代碼如下:
class Solution:def myPow(self, x: float, n: int) -> float:judge = Trueif n < 0:n = -njudge = Falsefinal = 1while n>0:if n%2 == 0:x *=xn //= 2final *= xn -= 1return final if judge else 1/final
python位運算符簡介
其實跟上面的方法類似,只是通過位運算符判斷奇偶性并且進行除以2的操作(移位操作)。代碼如下:
class Solution:def myPow(self, x: float, n: int) -> float:judge = Trueif n < 0:n = -njudge = Falsefinal = 1while n>0:if n & 1: #代表是奇數(shù)final *= xx *= xn >>= 1 # 右移一位return final if judge else 1/final類型二:求n次方
實現(xiàn) pow(x, n),即計算 x 的 n 次冪函數(shù)。其中x大于0,n為大于1整數(shù)。
解法:二分法求開方思路就是逐步逼近目標值。以x大于1為例:
設(shè)定結(jié)果范圍為[low, high],其中l(wèi)ow=0, high = x,且假定結(jié)果為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的數(shù),因為負數(shù)無法開平方(不考慮復數(shù)情況)if x>1:low,high = 0,xelse:low,high =x,1while True:r = (low+high)/2judge = 1for i in range(n):judge *= rif x >1 and judge>x:break # 對于大于1的數(shù),如果當前值已經(jīng)大于它本身,則無需再算下去if x <1 and judgeif abs(judge-x)<0.0000001: # 判斷是否達到精度要求print(pow(x,1/n)) # pow函數(shù)計算結(jié)果return relse:if judge>x:high = relse:low = r
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法2. JSP數(shù)據(jù)交互實現(xiàn)過程解析3. windows服務(wù)器使用IIS時thinkphp搜索中文無效問題4. .NET中l(wèi)ambda表達式合并問題及解決方法5. Nginx+php配置文件及原理解析6. 淺談python出錯時traceback的解讀7. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向8. Ajax實現(xiàn)表格中信息不刷新頁面進行更新數(shù)據(jù)9. Python importlib動態(tài)導入模塊實現(xiàn)代碼10. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解
