how to find cube root
How to Find Cube Root in Python
0
The cube root means a number that produces a given number when cubed. The cube root of a number is a value which when multiplied by itself thrice or three times, produces the original value.
The cube root symbol is denoted by '3√'. In the case of square root, we have used just the root symbol such as '√', which is also called a radical.
For example, the cube root of 64, denoted as 3√64, is 4 because when we multiply 4 by itself three times, we get 4 x 4 x 4 = 64 = 43.
Cube Root in Python
To calculate Python cube root, use the simple math equation: x ** (1. / 3) to compute the (floating-point) cube root of x. This simple math equation takes the cube root of x, rounds it to the nearest integer, raises it to the third power, and checks whether the result equals x.
x = 27 cr = x ** (1./3.) print(cr)
Output
3.0
To calculate the exponent number in Python, we use the **. The double star(**) is also called the power operator. To calculate the cube root, we can set the power equal to 1/3.
Find a cube root of a negative number in Python.
We can not find the cube root of the negative numbers the way we calculated for the above method. For example, the cube root of integer -27 should be -3, but Python returns 1.5000000000000004+2.598076211353316j.
To find the cube root of a negative number in Python, first, you need to use the abs() function, and then you can use the simple math equation to calculate.
Let's write a complete function that will check if the input number is negative, then it will calculate accordingly.
def cuberoot(x): if x < 0: x = abs(x) cube_root = x**(1/3)*(-1) else: cube_root = x**(1/3) return cube_root print(cuberoot(27)) print(round(cuberoot(-27)))
Output
3.0 -3
As you can see, we need to round the result to get the cube root's exact value.
Using Numpy cbrt() function
To find a cube root in Python, use the numpy library's cbrt() method. The np.cbrt() function returns the cube root of every element of the array.
Numpy cbrt() is a mathematical method that is used to find the cube root of every element in a given array.
import numpy as np arr1 = [1, 8, 27, 64] arr2 = np.cbrt(arr1) print(arr2)
Output
[1. 2. 3. 4.]
The np.cbrt() function is the easiest method to calculate a number's cube root. It does not get in trouble with negative inputs and returns the exact number like 4 for input 64, unlike the above approaches.
That is it for this tutorial.
Krunal 1151 posts 205 comments
Krunal Lathiya is an Information Technology Engineer. By profession, he is a web developer with knowledge of multiple back-end platforms (e.g., PHP, Node.js, Python) and frontend JavaScript frameworks (e.g., Angular, React, and Vue).
report this ad
how to find cube root
Source: https://appdividend.com/2021/06/14/how-to-find-cube-root-in-python/
Posted by: coreyittly1942.blogspot.com
This site uses Akismet to reduce spam. Learn how your comment data is processed.