Python math.cbrt() 方法用于计算给定数字的立方根。
在数学上,立方根法(表示为 ∛x)是一种数学运算,它找到一个数字,当该数字乘以自身两次时,得到原始数字 x。在数学上,这表示为 -
∛x = y such that y3 = x
例如,如果 x = 8,则 8(∛8) 的立方根为 2,因为 23 = 8。同样,如果 x = -27,则 -27(∛-27) 的立方根为 -3,因为 (-3)3 = -27。
语法
以下是 Python math.cbrt() 方法的基本语法 -
math.cbrt(x)
参数
此方法接受整数或浮点数作为要计算 cube 根的参数。
返回值
该方法返回给定值的 cube 根。返回值也是浮点数。
示例 1
在下面的示例中,我们使用 math.cbrt() 方法计算正整数的立方根 -
import math
result = math.cbrt(27)
print("Cube root of 27:", result)
输出
获得的输出如下 -
Cube root of 27: 3.0
示例 2
在这里,我们使用 math.cbrt() 方法计算负整数的立方根 -
import math
result = math.cbrt(-64)
print("Cube root of -64:", result)
输出
以下是上述代码的输出 -
Cube root of -64: -4.0
示例 3
在此示例中,我们使用 math.cbrt() 方法 − 计算 x=3 和 x + 1 的立方根之和
import math
x = 81
result = math.cbrt(x) + math.cbrt(x+1)
print("cube root obtained is:", result)
输出
我们得到的输出如下所示 -
cube root obtained is: 8.671230196690837
示例 4
现在,我们使用 math.cbrt() 方法来计算负浮点数的立方根 -
import math
result = math.cbrt(-125.0)
print("Cube root of -125.0:", result)
输出
生成的结果如下所示 -
Cube root of -125.0: -5.0