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
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
That’s it.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.