Finding the matrix hyperbolic tangent function using Taylor series.
Here’s an example program in Java that calculates the hyperbolic tangent function for a given matrix using the Taylor series approximation:
import java.util.Arrays; public class MatrixHyperbolicTangent { private static final int MAX_ITERATIONS = 10; // Maximum number of iterations for Taylor series private static final double EPSILON = 1e-10; // Tolerance for convergence // Calculates the hyperbolic tangent of a scalar value using the Taylor series private static double tanh(double x) { double result = 0.0; double term = x; int n = 1; while (Math.abs(term) > EPSILON && n <= MAX_ITERATIONS) { result += term; term = (term * x * x) / ((2 * n + 1) * (1 - term)); n++; } return result; } // Calculates the hyperbolic tangent of a matrix using the Taylor series private static double[][] tanh(double[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; double[][] result = new double[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i][j] = tanh(matrix[i][j]); } } return result; } public static void main(String[] args) { double[][] matrix = { { 1.0, 2.0 }, { -1.0, 0.5 } }; double[][] tanhMatrix = tanh(matrix); // Print the original matrix System.out.println("Original Matrix:"); for (double[] row : matrix) { System.out.println(Arrays.toString(row)); } // Print the matrix with hyperbolic tangent values System.out.println("\nTanh Matrix:"); for (double[] row : tanhMatrix) { System.out.println(Arrays.toString(row)); } } }
In this program, the `tanh()` method calculates the hyperbolic tangent of a scalar value using the Taylor series approximation. The `tanh(double[][] matrix)` method applies this calculation to each element of the input matrix.
The program demonstrates the usage of the `tanh()` method by calculating the hyperbolic tangent of a 2×2 matrix and printing the original matrix and the resulting matrix with hyperbolic tangent values.
Please note that the Taylor series approximation for the hyperbolic tangent function may not be accurate for large values or matrices with elements far from zero.
No comments yet! You be the first to comment.