# Return the cube-root of an array elementwise in Numpy

To calculate the cube root of a number in Python, you can use math.pow() function or the built-in exponentiation operator ** or np.cbrt() function.

Чтобы извлечь и вычислить кубический корень числа в Python, вы можете использовать функцию math.pow(), встроенный оператор возведения в степень ** или функцию np.cbrt().

## Using the math. pow() function

To find the cube root of a number using math.pow() function, you can raise the number to the power of (1/3).

number = 27

# Calculate the cube root using math.pow()
cube_root = math.pow(number, 1/3)

print(«Cube root of», number, «is:», cube_root)

In this post, you will learn different ways to find the cube root of a number in the Python programming language.

The cube root of a number is the factor that we multiply by itself three times to get that number. In mathematics, the cube root of a number x is a number y, if y³ = x.

When it is required to find the cube root of values, a function present in SciPy library can be used.

Syntax of ‘cbrt’ function

The ‘x’ is the parameter that is passed to the function ‘cbrt’ that is present in ‘special’ class of ‘SciPy’ library. Here’s an example −

## Using the Numpy cbrt() function

The numpy library provides a cbrt() function to compute the cube root of a number or an array of numbers. To calculate a cube root of a number or array of numbers in numpy, you can use the np.cbrt() method.

import numpy as np

number = 27

# Calculate the cube root using numpy.cbrt()
cube_root = np.cbrt(number)

print(«Cube root of», number, «is:», cube_root)

You can also find the cube root of multiple numbers at once by passing a list or an array to the numpy.cbrt() function.

import numpy as np

arr2 = np.cbrt(arr1)

The np.cbrt() function is the easiest method to calculate a number’s cube root. Unlike the above approaches, it does not get in trouble with negative inputs and returns the exact number like 4 for input 64.

That is it for this tutorial.

Mathematically, a cube root of a certain number is defined as a value obtained when the number is divided by itself thrice in a row. It is the reverse of a cube value. For example, the cube root of 216 is 6, as 6 × 6 × 6 = 216. Our task in this article is to find the cube root of a given number using python.

There are various ways in python to calculate the cube root of a number. Let us look at them one by one below −

### Input Output Scenarios

Let us now look at some input output scenarios to calculate thee cube root of a given number −

Assume the given input number is positive, the output is displayed as −

Дополнительно:  Android-Firewall

Input: 8
Result: 2

Assume the given input is negative, the output is displayed as −

Input: -8
Result: -2

Assume the input is a list of elements, the output is obtained as −

## Using the exponentiation operator

You can use the simple math equation: x ** (1. / 3) to calculate the cube root of a number in Python. It calculates the (floating-point) cube root of x.

It is a simple math equation that 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.)

The double star(**) is also called the power operator. To calculate the cube root, we can set the power equal to 1/3.

### Finding a cube root of a negative number in Python

To find the cube root of a negative number in Python, first, use the abs() function, and then you can use the simple math equation to calculate the cube root.

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.

if x < 0:
x = abs(x)
cube_root = x**(1/3)*(-1)

cube_root = x**(1/3)

As you can see, we need to round the result to get the cube root’s exact value.

To return the cube-root of an array, element-wise, use the numpy.cbrt() method in Python Numpy. An array of the same shape as x, containing the cube cube-root of each element in x. If out was provided, y is a reference to it. This is a scalar if x is a scalar.

The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

## Использование оператора возведения в степень

Вы можете использовать простое математическое уравнение: x **(1./3) для вычисления кубического корня числа в Python. Он вычисляет кубический корень (с плавающей запятой) из x.

Это простое математическое уравнение, которое извлекает кубический корень из х, округляет его до ближайшего целого числа, возводит в третью степень и проверяет, равен ли результат х.

Двойная звезда(**) также называется степенным оператором. Чтобы вычислить кубический корень, мы можем установить мощность, равную 1/3.

### Нахождение кубического корня отрицательного числа в Python

Чтобы найти кубический корень из отрицательного числа в Python, сначала используйте функцию abs(), а затем можно использовать простое математическое уравнение для вычисления кубического корня.

Мы не можем найти кубический корень из отрицательных чисел так, как мы рассчитали для вышеуказанного метода. Например, кубический корень из целого числа -27 должен быть равен -3, но Python возвращает 1,50000000000000004+2,598076211353316j.

Как видите, нам нужно округлить результат, чтобы получить точное значение кубического корня.

Дополнительно:  Cap root ca cer скачать

## Example

In the python program below, we find the cube root of a positive input number

math

num

cube_root mathnum

«Cube root of » num » is » cube_root

The output achieved is −

Cube root of 64 is 3.9999999999999996

### For Negative Numbers

In the python program below, we find the cube root of a negative input number.

Cube root of -64 is -3.9999999999999996

## Using Mathematical Equation

Given below is a python program that computes the cube root of a positive number.

num

cube_root num

«Cube root of » num » is » cube_root

The output of the above python code is −

Cube root of 216 is 5.999999999999999

Given below is a python program that computes the cube root of a negative number.

Cube root of -216 is -5.999999999999999

## Steps

At first, import the required library −

Create an array using the array() method −

Display the array −

Get the type of the array −

Get the dimensions of the Array −

Get the shape of the Array −

To return the cube-root of an array, element-wise, use the numpy.cbrt() method in Python Numpy −

## Python cube root using the cbrt() function

The cbrt() function of numpy module is used to find the cube root of a number. This function accepts a number in the first argument and the exponent or power of the number in the second argument. To use this method, the numpy module needs to be installed.

Here, we have defined a function to calculate the cube root using the cbrt() function.

import numpy as np

print(«Cube root of 198:»,np.cbrt(198))

print(»
Cube root of -8:»,np.cbrt(-8))

print(»
Cube root of 64:»,np.cbrt(64))

print(»
Cube root of 27:»,np.cbrt(27))

Output of the above code:

Cube root of 198: 5.8284766832514565
Cube root of -8:-2.0
Cube root of 64:4.0
Cube root of 27:3.0000000000000004

## Использование функции math. pow()

Чтобы найти кубический корень числа с помощью функции math.pow(), вы можете возвести число в степень(1/3).

In the given example, we are finding the cube root of a negative number using the Python programming language. For this, we need to use the abs() function, and then we can use the simple math equation to calculate.

def findcuberoot(num):
if num < 0:
num = abs(num)
cuberoot = num**(1/3)*(-1)
else:
cuberoot = num**(1/3)
return cuberoot

print(«Cube root of 729 : «,findcuberoot(729))
print(«Cube root of -729 : «,round(findcuberoot(-729)))

Cube root of 729 : 8.999999999999998
Cube root of -729 : -9

Find the stop words in nltk Python Eye Detection Program in Python OpenCV Python OpenCV Histogram of Grayscale Image Install NLTK for Python on Windows 64 bit Python program to map two lists into a dictionary Python program to input week number and print week dayPython program to list even and odd numbers of a list Python program to print odd numbers within a given range Python program to multiply two numbers Program to find area of triangle in Python Find area of rectangle in Python Swapping of two numbers in Python Find average of n numbers in Python Print multiplication table in Python Python program to multiply two matrices Python program to find area of circle Python iterate list with index Python add list to list Python random choice Python dict inside list Count consonants in a string Python Convert array to list Python

Дополнительно:  Не работает кулер на ноутбуке - причины и их решение

## Explanation

The pow() function from the Python math module is the easiest way to find the cube root of a number. The pow() function of Python returns the power of a number. This function accepts a number as the first argument and the exponent or power of the number as the second argument.

Here, we have defined a function to calculate the cube root.

def cube_root(x):
if x < 0:
x = abs(x)
cube_root = pow(x,1/3)*(-1)
else:
cube_root = pow(x,1/3)

return cube_root

print(«Cube root of 198:»,cube_root(198))

print(»
Cube root of 8:»,cube_root(8))

print(»
Cube root of 85:»,cube_root(85))

print(»
Cube root of 39:»,cube_root(39))

Cube root of 198: 5.828476683251456

Cube root of 8: 2.0

Cube root of 85: 4.396829672158179

Cube root of 39: 3.3912114430141664

## Using numpy’s cbrt() function

cbrt() is a built-in function in the numpy library that returns the cube root of every element present in an array inputted. This method does not raise an error while finding the cube root of a negative number therefore making it more efficient than previous approaches.

In the python example below, we are taking inputs using python lists and using cbrt() function we find the cube root.

On compiling and executing the python code above, the output can be obtained as −

## Использование функции Numpy cbrt()

Библиотека numpy предоставляет функцию cbrt() для вычисления кубического корня числа или массива чисел. Чтобы вычислить кубический корень числа или массива чисел в numpy, вы можете использовать метод np.cbrt().

Вы также можете найти кубический корень сразу из нескольких чисел, передав список или массив функции numpy.cbrt().

Функция np.cbrt() — самый простой способ вычислить кубический корень числа в Питон. В отличие от описанных выше подходов, он не вызывает проблем с отрицательными входными данными и возвращает точное число, например 4, для входного значения 64.

## Python cube root using the exponent symbol **

The exponent operator (**) returns the result of raising the first operand to the power of the second operand. In Python, we can use this exponent symbol to calculate the cube root of a number. It is also called a power operator. However, we cannot calculate the cube root of the negative numbers by using this method correctly.

Here, we have defined a function cube_root() to calculate the cube root of a number using the exponent symbol.

def cube_root(x):
if x < 0:
x = abs(x)
cube_root = x**(1/3)*(-1)
else:
cube_root = x**(1/3)
return cube_root

print(«Cube root of 181:»,cube_root(181))

print(»
Cube root of 21:»,cube_root(21))

print(»
Cube root of 81:»,cube_root(81))

print(»
Cube root of 27:»,cube_root(27))

Cube root of 181 5.65665282582291

Cube root of 21 2.7589241763811203

Cube root of 81 4.3267487109222245

Cube root of 27 3.0

When it is required to find the 10**x of an element or a list of elements, a function named ‘exp10’ present in SciPy library can be used.

Syntax of ‘exp10’ function

The ‘x’ is the parameter that is passed to the function ‘exp10’ that is present in ‘special’ class of ‘SciPy’ library.

Оцените статью