Python程式計算給定數字的立方根

WBOY
發布: 2023-08-19 12:33:07
轉載
2724 人瀏覽過

Python程式計算給定數字的立方根

數學上,一個特定數的立方根被定義為當這個數連續三次被自己除時所得到的值。它是一個立方數的反向操作。例如,216的立方根是6,因為6 × 6 × 6 = 216。本文的任務是使用Python找到給定數的立方根。

The cube root is represented using the symbol “$\mathrm{\sqrt[3]{a}}$”. The 3 in the symbol denotes that the value is divided thrice in order to achieve the cube root.

#在Python中,有多種方法可以計算出一個數的立方根。讓我們逐一來看它們:

  • 使用一個簡單的數學公式。

  • 使用math.pow()函數。

  • 使用cbrt()函數在numpy中。

輸入輸出場景

現在讓我們來看一些輸入輸出場景,以計算給定數字的立方根 -

假設給定的輸入數字為正數,輸出顯示為 −

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))
登入後複製

輸出

The output of the above python code is −

#
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{1rd}{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庫中的一個內建函數,它會傳回輸入陣列中每個元素的立方根。此方法在計算負數的立方根時不會引發錯誤,因此比之前的方法更有效率。

Example

在下面的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.]
登入後複製

以上是Python程式計算給定數字的立方根的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!