Python math.tanh() Method

The math.tanh() method returns the hyperbolic tangent of a given number.

Syntax

import math
math.tanh(num)

Parameters

num(required): A number for which you want to calculate the hyperbolic tangent.

Return Value

Returns a float value ranging from -1 to 1, representing hyperbolic tangent of  a number.

If the num is not a number, it returns TypeError.

Visual Representation

Visual Representation of Python math.tanh() Method

Example 1: How to Use math.tanh() Method

import math

# Calculate the hyperbolic tangent of different numbers
print (math.tanh(1))
print (math.tanh(3))
print (math.tanh(-3))
print (math.tanh(15.35))

Output

0.7615941559557649
0.9950547536867305
-0.9950547536867305
0.9999999999999071

Example 2: Plotting

import matplotlib.pyplot as plt
import math

# Create a list of x values from -2 to 2
x = [i * 0.01 for i in range(-200, 201)]

# Calculate the corresponding y values
y = [math.tanh(i) for i in x]

# Create a new figure
plt.figure()

# Plot x against y
plt.plot(x, y)

# Set the title
plt.title('Plot of tanh(x)')

# Set the x and y axis labels
plt.xlabel('x')
plt.ylabel('tanh(x)')

# Display the plot
plt.show()

Output

Plotting the math.tanh() Method

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.