NumPy tanh()

The tanh() function calculates the hyperbolic tangent of each element in an array.

Example

import numpy as np

# create an array of values
values = np.array([-2, -1, 0, 1, 2])

# calculate the hyperbolic tangent of each value result = np.tanh(values)
print(result) # Output:[-0.96402758 -0.76159416 0. 0.76159416 0.96402758]

tanh() Syntax

The syntax of tanh() is:

numpy.tanh(x, out = None, where = True, dtype = None)

tanh() Arguments

The tanh() method takes following arguments:

  • x - an input array
  • out (optional) - the output array where the result will be stored
  • where (optional) - a boolean array or condition indicating where to compute the hyperbolic tangent
  • dtype (optional) - data type of the output array

tanh() Return Value

The tanh() method returns an array with the corresponding hyperbolic tangent values of its elements.


Example 1: Use of out and where in tanh()

import numpy as np

values = np.array([-1, 0, 1, 2, 3])

# create an output array of the same shape and data type as 'values', filled with zeros
result = np.zeros_like(values, dtype=float)  

# calculate the hyperbolic tangent where values>=0 and store in result np.tanh(values, out=result, where=(values >= 0))
print(result)

Output

[0.         0.         0.76159416 0.96402758 0.99505475]

Here,

  • out=result specifies that the output of the np.tanh() function should be stored in the result array
  • where=(values >= 0) specifies that the hyperbolic operation should only be applied to elements in values that are greater than or equal to 0.

Example 2: Use of dtype Argument in tanh()

import numpy as np

# create an array of values
values = np.array([-0.5, -0.2, 0, 0.2, 0.5])

# calculate the hyperbolic tangent of each value with a specific dtype
tanh_values_float = np.tanh(values, dtype=float)
tanh_values_complex = np.tanh(values, dtype=complex)

print("Hyperbolic tangents with 'float' dtype:")
print(tanh_values_float)

print("\nHyperbolic tangents with 'complex' dtype:")
print(tanh_values_complex)

Output

Hyperbolic tangents with 'float' dtype:
[-0.46211716 -0.19737532  0.          0.19737532  0.46211716]

Hyperbolic tangents with 'complex' dtype:
[-0.46211716+0.j -0.19737532+0.j  0.        +0.j  0.19737532+0.j
  0.46211716+0.j]

Here, by specifying the desired dtype, we can specify the data type of the output array according to our requirements.

Note: To learn more about the dtype argument, please visit NumPy Data Types.