数学上,一个特定数的立方根被定义为当这个数连续三次被自己除时所得到的值。它是一个立方数的反向操作。例如,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: 8Result: 2
登录后复制
假设给定的输入是负数,则输出显示为 −
Input: -8Result: -2
登录后复制
假设输入是一个元素列表,输出是通过以下方式获得的 –
Input: [8, -125]Result: [2, -5]
登录后复制
使用数学方程
让我们从简单开始;我们使用一个简单的数学方程在Python中找到一个数的立方根。在这里,我们找到输入数字的$mathrm{rac{1}{3}}$次方。
示例1:对于正数
给定的是一个计算正数立方根的Python程序。
#take an input numbernum = 216#calculate cube rootcube_root = num ** (1/3)#display the outputprint("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 numbernum = -216#calculate cube rootcube_root = -(-num) ** (1/3)#display the outputprint("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{rac{1rd}{3}}$次幂。
示例1:对于正数
在下面的Python程序中,我们找到一个正输入数的立方根
import math#take an input numbernum = 64#calculate cube rootcube_root = math.pow(num, (1/3))#display the outputprint("Cube root of ", str(num), " is ", str(cube_root))
登录后复制
输出
实现的输出为−
Cube root of 64 is 3.9999999999999996
登录后复制
例子2:对于负数
在下面的Python程序中,我们找到了一个负输入数的立方根。
import math#take an input numbernum = -64#calculate cube rootcube_root = -math.pow(-num, (1/3))#display the outputprint("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() functionimport numpy as np#take an input listnum = [64, -729]#calculate cube root of each element in the listcube_root = np.cbrt(num)#display the outputprint("Cube root of ", str(num), " is ", str(cube_root))
登录后复制
输出
在编译和执行上述Python代码时,可以获得以下输出 –
Cube root of [64, -729] is [ 4. -9.]
登录后复制
以上就是Python程序计算给定数字的立方根的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2227327.html