
数学上,一个特定数的立方根被定义为当这个数连续三次被自己除时所得到的值。它是一个立方数的反向操作。例如,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中,有多种方法可以计算一个数的立方根。让我们逐个来看一下它们:
-
使用一个简单的数学公式。
立即学习“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.]










