Search Docs…

Search Docs…

Guide

Math library template - CuPy


This template serves as a solid foundation for a professional math library. You can expand it by adding more modules, refining error handling, and incorporating more advanced algorithms or GPU-accelerated routines as needed.


"""
mymathlib: A Professional Mathematical Library Template

This library provides high-performance implementations of common mathematical operations,
including linear algebra, calculus, and combinatorial functions.

Modules:
    - linear_algebra: Contains classes and functions for matrix operations.
    - calculus: Contains numerical integration methods.
    - utils: Contains miscellaneous utility functions (e.g., factorial).

Author: Your Name
Date: 2025-02-03
License: MIT License
"""

from __future__ import annotations
from typing import List, Callable

# =============================================================================
# Linear Algebra Module
# =============================================================================

class Matrix:
    """
    A simple Matrix class to perform basic linear algebra operations.

    Attributes:
        data (List[List[float]]): 2D list containing the matrix elements.
        rows (int): Number of rows.
        cols (int): Number of columns.
    """
    
    def __init__(self, data: List[List[float]]) -> None:
        if not data or not data[0]:
            raise ValueError("Data must be a non-empty 2D list.")
        self.data = data
        self.rows = len(data)
        self.cols = len(data[0])
    
    def __str__(self) -> str:
        return "\n".join(["\t".join(map(str, row)) for row in self.data])
    
    def __add__(self, other: Matrix) -> Matrix:
        """
        Add two matrices element-wise.

        Args:
            other (Matrix): The matrix to add.

        Returns:
            Matrix: The result of the addition.
        """
        if self.rows != other.rows or self.cols != other.cols:
            raise ValueError("Matrices must have the same dimensions to add.")
        result = [
            [self.data[i][j] + other.data[i][j] for j in range(self.cols)]
            for i in range(self.rows)
        ]
        return Matrix(result)
    
    def __mul__(self, other: Matrix) -> Matrix:
        """
        Multiply two matrices using the dot product.

        Args:
            other (Matrix): The matrix to multiply with.

        Returns:
            Matrix: The result of the multiplication.

        Raises:
            ValueError: If the matrices have incompatible dimensions.
        """
        if self.cols != other.rows:
            raise ValueError("Invalid dimensions for matrix multiplication.")
        result = [
            [sum(self.data[i][k] * other.data[k][j] for k in range(self.cols))
             for j in range(other.cols)]
            for i in range(self.rows)
        ]
        return Matrix(result)
    
    def transpose(self) -> Matrix:
        """
        Transpose the matrix.

        Returns:
            Matrix: The transposed matrix.
        """
        transposed = [
            [self.data[i][j] for i in range(self.rows)]
            for j in range(self.cols)
        ]
        return Matrix(transposed)

# =============================================================================
# Calculus Module
# =============================================================================

def numerical_integration(
    f: Callable[[float], float], 
    a: float, 
    b: float, 
    n: int = 1000
) -> float:
    """
    Approximates the integral of a function f over the interval [a, b]
    using the trapezoidal rule.

    Args:
        f (Callable[[float], float]): The function to integrate.
        a (float): The start of the interval.
        b (float): The end of the interval.
        n (int, optional): The number of subintervals. Default is 1000.

    Returns:
        float: The approximate value of the integral.
    """
    h = (b - a) / n
    total = 0.5 * (f(a) + f(b))
    for i in range(1, n):
        total += f(a + i * h)
    return total * h

# =============================================================================
# Utility Module
# =============================================================================

def factorial(n: int) -> int:
    """
    Compute the factorial of a non-negative integer n recursively.

    Args:
        n (int): A non-negative integer.

    Returns:
        int: The factorial of n.

    Raises:
        ValueError: If n is negative.
    """
    if n < 0:
        raise ValueError("n must be a non-negative integer.")
    return 1 if n in (0, 1) else n * factorial(n - 1)

# =============================================================================
# Example Usage and Testing
# =============================================================================

if __name__ == "__main__":
    # Demonstrate Matrix operations
    A = Matrix([[1, 2], [3, 4]])
    B = Matrix([[5, 6], [7, 8]])
    
    print("Matrix A:")
    print(A)
    print("\nMatrix B:")
    print(B)
    
    print("\nA + B:")
    print(A + B)
    
    print("\nA * B:")
    print(A * B)
    
    print("\nTranspose of A:")
    print(A.transpose())
    
    # Demonstrate numerical integration: integrate f(x) = x^2 over [0, 1]
    f = lambda x: x ** 2
    integral_value = numerical_integration(f, 0, 1)
    print("\nNumerical integration of x^2 from 0 to 1:")
    print(integral_value)
    
    # Demonstrate factorial computation

  
  
  
  
  
  
  print("\nFactorial of 5:")
    print(factorial(5))


Modular Structure:
The code is divided into logical sections (linear algebra, calculus, utilities), which makes it easier to maintain and extend.

  • Docstrings and Type Hints:
    Every function and class includes a docstring explaining its purpose, arguments, return values, and exceptions. Type hints help improve readability and assist static analysis tools.

  • Usage Example:
    The if __name__ == "__main__": block serves as a simple test and usage example. In a production-quality library, you would typically add a dedicated test suite (e.g., using unittest or pytest).

written by: Matthew Drabek

By Matthew Drabek & Digital Trans4orMation Team

© 2024

By Matthew Drabek & Digital Trans4orMation Team

© 2024