Mastering mpmath Comprehensive Guide and API Examples

Introduction to mpmath

mpmath is a Python library for arbitrary-precision floating-point arithmetic. It is widely used for numerical analysis and enables computations with large numbers of digits beyond the built-in precision of Python’s float type.

Getting Started

To install mpmath, use the following command:

 pip install mpmath 

Basic Usage

Here are some basic operations with mpmath:

  from mpmath import mp
# Set precision mp.dps = 50  # 50 decimal places
# Basic arithmetic print(mp.sqrt(2))  # Square root print(mp.exp(1))   # Exponential function print(mp.pi)       # Pi constant  

Advanced Functions

mpmath provides many advanced mathematical functions. Here are some examples:

  from mpmath import mp
# Gamma function print(mp.gamma(0.5))  
# Riemann zeta function print(mp.zetac(2))    
# Bessel functions print(mp.besselk(0, 1))    

Matrix Operations

mpmath supports matrix operations. Below is an example:

  from mpmath import mp, matrix
A = matrix([[1, 2], [3, 4]]) B = matrix([[2, 0], [1, 2]])
# Matrix multiplication print(A * B)
# Matrix inverse print(A**-1)  

Solving Equations

mpmath can solve equations numerically. Here’s an example solving the quadratic equation:

  from mpmath import mp, findroot
# Function for the quadratic equation x^2 - 2x + 1 = 0 def f(x):
    return x**2 - 2*x + 1

# Finding the root root = findroot(f, 1) print(root)  

Integration and Differentiation

  from mpmath import mp, quad, diff
# Define a function def g(x):
    return mp.exp(-x**2)

# Integration from -Inf to Inf integral = quad(g, [-mp.inf, mp.inf]) print(integral)
# Differentiation at a point derivative = diff(g, 1) print(derivative)  

Application Example

Here’s a complete example of how to use various mpmath functions to solve a mathematical problem:

  from mpmath import mp, matrix, quad, diff, findroot
# Set precision mp.dps = 30
# Define a matrix A = matrix([[2, 3], [1, 4]])
# Calculate the inverse A_inv = A**-1
# Define a quadratic function def h(x):
    return x**2 + 3*x + 2

# Find the root root = findroot(h, 0)
# Integrate a function def k(x):
    return mp.sin(x)

integral_k = quad(k, [0, mp.pi])
# Differentiate the quadratic function derivative_h = diff(h, 1)
print(f"Inverse of A:\n{A_inv}") print(f"Root of h(x): {root}") print(f"Integral of sin(x) from 0 to pi: {integral_k}") print(f"Derivative of h(x): {derivative_h}")  

This example demonstrates the versatility of mpmath in handling matrices, solving equations, performing integrations, and differentiations with high precision.


Hash: 746f76ead96ca3918efd851fb7299ee617999c0c6baedf9584747cb2b01bc68f

Leave a Reply

Your email address will not be published. Required fields are marked *