Python程式計算給定數字的立方根
從數學角度來看,某個數字的立方根是指將該數字連續除以自身三次後得到的值。它是立方值的逆運算。例如,216的立方根是6,因為6 × 6 × 6 = 216。本文的任務是使用Python查詢給定數字的立方根。
立方根用符號“$\mathrm{\sqrt[3]{a}}$”表示。符號中的3表示為了獲得立方根,該值需要連續除以自身三次。
Python中有多種方法可以計算數字的立方根。讓我們逐一檢視以下方法:
使用簡單的數學公式。
使用math.pow()函式。
使用numpy中的cbrt()函式。
輸入輸出場景
現在讓我們來看一些輸入輸出場景,以計算給定數字的立方根:
假設給定的輸入數字為正數,則輸出顯示為:
Input: 8 Result: 2
假設給定的輸入為負數,則輸出顯示為:
Input: -8 Result: -2
假設輸入是一個元素列表,則輸出結果為:
Input: [8, -125] Result: [2, -5]
使用數學公式
讓我們從簡單開始;我們使用一個簡單的數學公式在Python中查詢數字的立方根。在這裡,我們找到輸入數字的$\mathrm{\frac{1}{3}}$次冪。
示例1:正數
下面是一個計算正數立方根的Python程式。
#take an input number num = 216 #calculate cube root cube_root = num ** (1/3) #display the output print("Cube root of ", str(num), " is ", str(cube_root))
輸出
上述Python程式碼的輸出為:
Cube root of 216 is 5.999999999999999
示例2:負數
下面是一個計算負數立方根的Python程式。
#take an input number num = -216 #calculate cube root cube_root = -(-num) ** (1/3) #display the output print("Cube root of ", str(num), " is ", str(cube_root))
輸出
Cube root of -216 is -5.999999999999999
使用math.pow()函式
math.pow(x, y)函式返回x的y次冪的值,條件是x始終為正值。因此,在這種情況下,我們使用此函式將輸入數字提高到其$\mathrm{\frac{1}{3}}$次冪。
示例1:正數
在下面的Python程式中,我們找到正輸入數字的立方根
import math #take an input number num = 64 #calculate cube root cube_root = math.pow(num, (1/3)) #display the output print("Cube root of ", str(num), " is ", str(cube_root))
輸出
獲得的輸出為:
Cube root of 64 is 3.9999999999999996
示例2:負數
在下面的Python程式中,我們找到負輸入數字的立方根。
import math #take an input number num = -64 #calculate cube root cube_root = -math.pow(-num, (1/3)) #display the output print("Cube root of ", str(num), " is ", str(cube_root))
輸出
獲得的輸出為:
Cube root of -64 is -3.9999999999999996
使用numpy的cbrt()函式
cbrt()是numpy庫中的一個內建函式,它返回輸入陣列中每個元素的立方根。此方法在查詢負數的立方根時不會引發錯誤,因此比以前的方法更有效。
示例
在下面的Python示例中,我們使用Python列表作為輸入,並使用cbrt()函式查詢立方根。
#import numpy library to access cbrt() function import numpy as np #take an input list num = [64, -729] #calculate cube root of each element in the list cube_root = np.cbrt(num) #display the output print("Cube root of ", str(num), " is ", str(cube_root))
輸出
編譯並執行上面的Python程式碼後,可以獲得以下輸出:
Cube root of [64, -729] is [ 4. -9.]
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP