w3resource

NumPy: Calculate hyperbolic sine, cosine, and tangent for all elements in a given array


Write a NumPy program to calculate hyperbolic sine, hyperbolic cosine, and hyperbolic tangent for all elements in a given array.

Sample Input: Input: Input: [-1., 0, 1.]

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array of values: [-1, 0, 1]
x = np.array([-1., 0, 1.])

# Computing hyperbolic sine (sinh) of each element in the array using np.sinh()
print(np.sinh(x))

# Computing hyperbolic cosine (cosh) of each element in the array using np.cosh()
print(np.cosh(x))

# Computing hyperbolic tangent (tanh) of each element in the array using np.tanh()
print(np.tanh(x)) 

Sample Output:

[-1.17520119  0.          1.17520119]
[1.54308063 1.         1.54308063]
[-0.76159416  0.          0.76159416]

Explanation:

x = np.array([-1., 0, 1.]): This code creates a NumPy array x with the values [-1., 0, 1.].

np.sinh(x) - The np.sinh(x) function calculates the hyperbolic sine of x, which is defined as (e^x - e^(-x))/2. For the given input, the output would be [-1.17520119e+00, 0.00000000e+00, 1.17520119e+00].

np.cosh(x) - The np.cosh(x) function calculates the hyperbolic cosine of x, which is defined as (e^x + e^(-x))/2. For the given input, the output would be [1.54308063, 1., 1.54308063].

np.tanh(x) - The np.tanh(x) function calculates the hyperbolic tangent of x, which is defined as sinh(x)/cosh(x). For the given input, the output would be [-0.76159416, 0., 0.76159416].

Python-Numpy Code Editor: