首页 > 后端开发 > Python教程 > Python程序计算给定数字的立方根

Python程序计算给定数字的立方根

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
发布: 2023-08-19 12:33:07
转载
2877 人浏览过

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中文网其他相关文章!

相关标签:
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
python - ubuntu16.04 lxml的报错
来自于 1970-01-01 08:00:00
0
0
0
有办法在PHP里写Python吗?
来自于 1970-01-01 08:00:00
0
0
0
python scrapy爬虫错误
来自于 1970-01-01 08:00:00
0
0
0
centos7 编译安装 Python 3.5.1 失败
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板