chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:32:53 +08:00
commit 2a16f2f53b
247 changed files with 69150 additions and 0 deletions
+253
View File
@@ -0,0 +1,253 @@
Basic usage
===========================
To avoid inadvertently overriding other functions or objects, explicitly import
only the needed objects, or use the ``mpmath.`` or ``mp.`` namespaces::
>>> from mpmath import sin
>>> sin(1)
mpf('0.8414709848078965')
>>> import mpmath
>>> mpmath.sin(1)
mpf('0.8414709848078965')
>>> from mpmath import mp # mp context object -- to be explained
>>> mp.sin(1)
mpf('0.8414709848078965')
.. note::
Importing everything with ``from mpmath import *`` can be convenient,
especially when using mpmath interactively, but is best to avoid such
import statements in production code, as they make it unclear which
names are present in the namespace and wildcard-imported names may
conflict with other modules or variable names.
Number types
------------
Mpmath provides the following numerical types:
+------------+----------------+
| Class | Description |
+============+================+
| ``mpf`` | Real float |
+------------+----------------+
| ``mpc`` | Complex float |
+------------+----------------+
| ``matrix`` | Matrix |
+------------+----------------+
The following section will provide a very short introduction to the types ``mpf`` and ``mpc``. Intervals and matrices are described further in the documentation chapters on interval arithmetic and matrices / linear algebra.
The ``mpf`` type is analogous to Python's built-in ``float``. It holds a real number or one of the special values ``inf`` (positive infinity), ``-inf`` (negative infinity) and ``nan`` (not-a-number, indicating an indeterminate result). You can create ``mpf`` instances from strings, integers, floats, and other ``mpf`` instances:
>>> from mpmath import mpf, mpc, mp
>>> mpf(4)
mpf('4.0')
>>> mpf(2.5)
mpf('2.5')
>>> mpf("1.25e6")
mpf('1250000.0')
>>> mpf(mpf(2))
mpf('2.0')
>>> mpf("inf")
mpf('inf')
The ``mpc`` type represents a complex number in rectangular form as a pair of ``mpf`` instances. It can be constructed from a Python ``complex``, a real number, or a pair of real numbers:
>>> mpc(2,3)
mpc(real='2.0', imag='3.0')
>>> mpc(complex(2,3)).imag
mpf('3.0')
You can mix ``mpf`` and ``mpc`` instances with each other and with Python numbers:
>>> mpf(3) + 2*mpf('2.5') + 1.0
mpf('9.0')
>>> mp.dps = 15 # Set precision (see below)
>>> mpc(1j)**0.5
mpc(real='0.70710678118654757', imag='0.70710678118654757')
Setting the precision
---------------------
Mpmath uses a global working precision; it does not keep track of the precision or accuracy of individual numbers. Performing an arithmetic operation or calling ``mpf()`` rounds the result to the current working precision. The working precision is controlled by a context object called ``mp``, which has the following default state:
>>> print(mp)
Mpmath settings:
mp.prec = 53 [default: 53]
mp.dps = 15 [default: 15]
mp.rounding = 'n' [default: 'n']
mp.trap_complex = False [default: False]
The term **prec** denotes the binary precision (measured in bits) while **dps** (short for *decimal places*) is the decimal precision. Binary and decimal precision are related roughly according to the formula ``prec = 3.33*dps``. For example, it takes a precision of roughly 333 bits to hold an approximation of pi that is accurate to 100 decimal places (actually slightly more than 333 bits is used).
Changing either precision property of the ``mp`` object automatically updates the other; usually you just want to change the ``dps`` value:
>>> mp.dps = 100
>>> mp.dps
100
>>> mp.prec
336
When the precision has been set, all ``mpf`` operations are carried out at that precision::
>>> mp.dps = 50
>>> mpf(1) / 6
mpf('0.1666666666666666666666666666666666666666666666666666')
>>> mp.dps = 25
>>> mpf(2) ** mpf('0.5')
mpf('1.41421356237309504880168871')
The precision of complex arithmetic is also controlled by the ``mp`` object:
>>> mp.dps = 10
>>> mpc(1,2) / 3
mpc(real='0.3333333333321', imag='0.6666666666642')
There is no restriction on the magnitude of numbers. An ``mpf`` can for example hold an approximation of a large Mersenne prime:
>>> mp.dps = 15
>>> print(mpf(2)**32582657 - 1)
1.24575026015369e+9808357
Or why not 1 googolplex:
>>> print(mpf(10) ** (10**100))
1.0e+100000000000000000000000000000000000000000000000000...
The (binary) exponent is stored exactly and is independent of the precision.
The ``rounding`` property control default rounding mode for the context:
>>> mp.rounding # round to nearest is the default
'n'
>>> sin(1)
mpf('0.8414709848078965')
>>> mp.rounding = 'u' # round up
>>> sin(1)
mpf('0.84147098480789662')
>>> mp.rounding = 'n'
Temporarily changing the precision
..................................
It is often useful to change the precision during only part of a calculation. A way to temporarily increase the precision and then restore it is as follows:
>>> mp.prec += 2
>>> # do_something()
>>> mp.prec -= 2
The ``with`` statement along with the mpmath functions ``workprec``, ``workdps``, ``extraprec`` and ``extradps`` can be used to temporarily change precision in a more safe manner:
>>> from mpmath import extradps, workdps
>>> with workdps(20):
... print(mpf(1)/7)
... with extradps(10):
... print(mpf(1)/7)
...
0.14285714285714285714
0.142857142857142857142857142857
>>> mp.dps
15
The ``with`` statement ensures that the precision gets reset when exiting the block, even in the case that an exception is raised.
The ``workprec`` family of functions can also be used as function decorators:
>>> @workdps(6)
... def f():
... return mpf(1)/3
...
>>> f()
mpf('0.33333331346511841')
Some functions accept the ``prec`` and ``dps`` keyword arguments and this will override the global working precision. Note that this will not affect the precision at which the result is printed, so to get all digits, you must either use increase precision afterward when printing or use ``nstr``/``nprint``:
>>> from mpmath import exp, nprint
>>> mp.dps = 15
>>> print(exp(1))
2.71828182845905
>>> print(exp(1, dps=50)) # Extra digits won't be printed
2.71828182845905
>>> nprint(exp(1, dps=50), 50)
2.7182818284590452353602874713526624977572470937
Finally, instead of using the global context object ``mp``, you can create custom contexts and work with methods of those instances instead of global functions. The working precision will be local to each context object:
>>> mp2 = mp.clone()
>>> mp.dps = 10
>>> mp2.dps = 20
>>> print(mp.mpf(1) / 3)
0.3333333333
>>> print(mp2.mpf(1) / 3)
0.33333333333333333333
**Note**: the ability to create multiple contexts is a new feature that is only partially implemented. Not all mpmath functions are yet available as context-local methods. In the present version, you are likely to encounter bugs if you try mixing different contexts.
Providing correct input
-----------------------
Note that when creating a new ``mpf``, the value will at most be as accurate as the input. *Be careful when mixing mpmath numbers with Python floats*. When working at high precision, fractional ``mpf`` values should be created from strings or integers:
>>> mp.dps = 30
>>> mpf(10.9) # bad
mpf('10.9000000000000003552713678800501')
>>> mpf(1090/100) # bad, beware Python's true division produces floats
mpf('10.9000000000000003552713678800501')
>>> mpf('10.9') # good
mpf('10.8999999999999999999999999999997')
>>> mpf(109) / mpf(10) # also good
mpf('10.8999999999999999999999999999997')
>>> mp.dps = 15
(Binary fractions such as 0.5, 1.5, 0.75, 0.125, etc, are generally safe as input, however, since those can be represented exactly by Python floats.)
Printing
--------
By default, the ``repr()`` of a number includes its type signature. This way ``eval`` can be used to recreate a number from its string representation:
>>> eval(repr(mpf(2.5)))
mpf('2.5')
Prettier output can be obtained by using ``str()`` or ``print``, which hide the ``mpf`` and ``mpc`` signatures and also suppress rounding artifacts in the last few digits:
>>> mpf("3.14159")
mpf('3.1415899999999999')
>>> print(mpf("3.14159"))
3.14159
>>> print(mpc(1j)**0.5)
(0.707106781186548 + 0.707106781186548j)
Setting the ``mp.pretty`` option will use the ``str()``-style output for ``repr()`` as well:
>>> mp.pretty = True
>>> mpf(0.6)
0.6
>>> mp.pretty = False
>>> mpf(0.6)
mpf('0.59999999999999998')
To use enough digits to be able recreate value exactly, set ``mp.pretty_dps``
to ``"repr"`` (default value is ``"str"``). Same option is used to control
default number of digits in the new-style string formatting *without format
specifier*, i.e. ``format(exp(mpf(1)))``.
The number of digits with which numbers are printed by default is determined by
the working precision. To specify the number of digits to show without
changing the working precision, use :func:`format syntax support
<mpmath.mpf.__format__>` or functions :func:`mpmath.nstr` and
:func:`mpmath.nprint`:
>>> a = mpf(1) / 6
>>> a
mpf('0.16666666666666666')
>>> f'{a:.8}'
'0.16666667'
>>> f'{a:.50}'
'0.16666666666666665741480812812369549646973609924316'
+23
View File
@@ -0,0 +1,23 @@
Function approximation
----------------------
Taylor series (``taylor``)
..........................
.. autofunction:: mpmath.taylor
Pade approximation (``pade``)
.............................
.. autofunction:: mpmath.pade
Chebyshev approximation (``chebyfit``)
......................................
.. autofunction:: mpmath.chebyfit
Fourier series (``fourier``, ``fourierval``)
............................................
.. autofunction:: mpmath.fourier
.. autofunction:: mpmath.fourierval
+19
View File
@@ -0,0 +1,19 @@
Differentiation
---------------
Numerical derivatives (``diff``, ``diffs``)
...........................................
.. autofunction:: mpmath.diff
.. autofunction:: mpmath.diffs
Composition of derivatives (``diffs_prod``, ``diffs_exp``)
..........................................................
.. autofunction:: mpmath.diffs_prod
.. autofunction:: mpmath.diffs_exp
Fractional derivatives / differintegration (``differint``)
............................................................
.. autofunction:: mpmath.differint
+14
View File
@@ -0,0 +1,14 @@
Numerical calculus
==================
.. toctree::
:maxdepth: 2
polynomials
optimization
sums_limits
differentiation
integration
odes
approximation
inverselaplace
+36
View File
@@ -0,0 +1,36 @@
Numerical integration (quadrature)
----------------------------------
Standard quadrature (``quad``)
..............................
.. autofunction:: mpmath.quad
Quadrature with subdivision (``quadsubdiv``)
............................................
.. autofunction:: mpmath.quadsubdiv
Oscillatory quadrature (``quadosc``)
....................................
.. autofunction:: mpmath.quadosc
Quadrature rules
................
.. autoclass:: mpmath.calculus.quadrature.QuadratureRule
:members:
Tanh-sinh rule
~~~~~~~~~~~~~~
.. autoclass:: mpmath.calculus.quadrature.TanhSinh
:members:
Gauss-Legendre rule
~~~~~~~~~~~~~~~~~~~
.. autoclass:: mpmath.calculus.quadrature.GaussLegendre
:members:
+71
View File
@@ -0,0 +1,71 @@
Numerical inverse Laplace transform
-----------------------------------
One-step algorithm (``invertlaplace``)
......................................
.. autofunction:: mpmath.invertlaplace
Specific algorithms
...................
Fixed Talbot algorithm
~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: mpmath.calculus.inverselaplace.FixedTalbot
:members:
Gaver-Stehfest algorithm
~~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: mpmath.calculus.inverselaplace.Stehfest
:members:
de Hoog, Knight & Stokes algorithm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: mpmath.calculus.inverselaplace.deHoog
:members:
Cohen acceleration algorithm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: mpmath.calculus.inverselaplace.Cohen
:members:
Manual approach
...............
It is possible and sometimes beneficial to re-create some of the
functionality in ``invertlaplace``. This could be used to compute the
Laplace-space function evaluations in a different way. For example,
the Laplace-space function evaluations could be the result of a
quadrature or sum, solution to a system of ordinary differential
equations, or possibly computed in parallel from some external library
or function call.
A trivial example showing the process (which could be implemented
using the existing interface):
>>> from mpmath import calculus, convert, exp, mp
>>> myTalbot = calculus.inverselaplace.FixedTalbot(mp)
>>> t = convert(0.25)
>>> myTalbot.calc_laplace_parameter(t)
>>> fp = lambda p: 1/(p + 1) - 1/(p + 1000)
>>> ft = lambda t: exp(-t) - exp(-1000*t)
>>> fpvec = [fp(p) for p in myTalbot.p]
>>> ft(t)-myTalbot.calc_time_domain_solution(fpvec,t,manual_prec=True)
mpf('1.92830017952889006175687218e-21')
This manual approach is also useful to look at the Laplace parameter,
order, or working precision which were computed.
>>> myTalbot.degree
34
Credit
......
The numerical inverse Laplace transform functionality was contributed
to mpmath by Kristopher L. Kuhlman in 2017. The Cohen method was contributed
to mpmath by Guillermo Navas-Palencia in 2022.
+7
View File
@@ -0,0 +1,7 @@
Ordinary differential equations
-------------------------------
Solving the ODE initial value problem (``odefun``)
..................................................
.. autofunction:: mpmath.odefun
+25
View File
@@ -0,0 +1,25 @@
Root-finding and optimization
-----------------------------
Root-finding (``findroot``)
...........................
.. autofunction:: mpmath.findroot(f, x0, solver=Secant, tol=None, verbose=False, verify=True, **kwargs)
Solvers
^^^^^^^
.. autoclass:: mpmath.calculus.optimization.Secant
.. autoclass:: mpmath.calculus.optimization.Newton
.. autoclass:: mpmath.calculus.optimization.MNewton
.. autoclass:: mpmath.calculus.optimization.Halley
.. autoclass:: mpmath.calculus.optimization.Muller
.. autoclass:: mpmath.calculus.optimization.Bisection
.. autoclass:: mpmath.calculus.optimization.Illinois
.. autoclass:: mpmath.calculus.optimization.Pegasus
.. autoclass:: mpmath.calculus.optimization.Anderson
.. autoclass:: mpmath.calculus.optimization.Ridder
.. autoclass:: mpmath.calculus.optimization.ANewton
.. autoclass:: mpmath.calculus.optimization.MDNewton
.. autoclass:: mpmath.calculus.optimization.ModAB
.. autoclass:: mpmath.calculus.optimization.Brent
+15
View File
@@ -0,0 +1,15 @@
Polynomials
-----------
See also :func:`~mpmath.taylor` and :func:`~mpmath.chebyfit` for
approximation of functions by polynomials.
Polynomial evaluation (``polyval``)
...................................
.. autofunction:: mpmath.polyval
Polynomial roots (``polyroots``)
................................
.. autofunction:: mpmath.polyroots
+67
View File
@@ -0,0 +1,67 @@
Sums, products, limits and extrapolation
----------------------------------------
The functions listed here permit approximation of infinite
sums, products, and other sequence limits.
Use :func:`mpmath.fsum` and :func:`mpmath.fprod`
for summation and multiplication of finite sequences.
Summation
..........................................
:func:`~mpmath.nsum`
^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.nsum
:func:`~mpmath.sumem`
^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.sumem
:func:`~mpmath.sumap`
^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.sumap
Products
...............................
:func:`~mpmath.nprod`
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.nprod
Limits (``limit``)
..................
:func:`~mpmath.limit`
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.limit
Extrapolation
..........................................
The following functions provide a direct interface to
extrapolation algorithms. :func:`~mpmath.nsum` and :func:`~mpmath.limit`
essentially work by calling the following functions with an increasing
number of terms until the extrapolated limit is accurate enough.
The following functions may be useful to call directly if the
precise number of terms needed to achieve a desired accuracy is
known in advance, or if one wishes to study the convergence
properties of the algorithms.
:func:`~mpmath.richardson`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.richardson
:func:`~mpmath.shanks`
^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.shanks
:func:`~mpmath.levin`
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.levin
:func:`~mpmath.cohen_alt`
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.cohen_alt
+8
View File
@@ -0,0 +1,8 @@
.. _cli:
Command-Line Usage
==================
When called as a program from the command line, the following form is used:
.. autoprogram:: mpmath.__main__:parser
+52
View File
@@ -0,0 +1,52 @@
"""
Mpmath documentation build configuration file.
This file is execfile()d with the current directory set to its
containing dir.
The contents of this file are pickled, so don't put values in the
namespace that aren't pickleable (module imports are okay, they're
removed automatically).
"""
import mpmath
# Add any Sphinx extension module names here, as strings.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax',
'sphinx.ext.intersphinx', 'sphinxcontrib.autoprogram',
'matplotlib.sphinxext.plot_directive']
# Sphinx will warn about all references where the target cannot be found.
nitpicky = True
# Project information.
project = mpmath.__name__
copyright = '2007-2026, Fredrik Johansson and mpmath developers'
release = version = mpmath.__version__
# Define how the current time is formatted using time.strftime().
today_fmt = '%B %d, %Y'
# The "theme" that the HTML output should use.
html_theme = 'classic'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [('index', 'mpmath.tex', 'mpmath documentation',
r'Fredrik Johansson \and mpmath contributors', 'manual')]
# The name of default reST role, that is, for text marked up `like this`.
default_role = 'math'
# Contains mapping the locations and names of other projects that
# should be linked to in this documentation.
intersphinx_mapping = {
'python': ('https://docs.python.org/3/', None),
'sympy': ('https://docs.sympy.org/latest/', None),
}
plot_include_source = True
plot_formats = [('png', 96), 'pdf']
plot_html_show_formats = False
plot_html_show_source_link = False
+370
View File
@@ -0,0 +1,370 @@
Contexts
========
High-level code in mpmath is implemented as methods on a "context object". The context implements arithmetic, type conversions and other fundamental operations. The context also holds settings such as precision, and stores cache data. A few different contexts (with a mostly compatible interface) are provided so that the high-level algorithms can be used with different implementations of the underlying arithmetic, allowing different features and speed-accuracy tradeoffs. Currently, mpmath provides the following contexts:
* Arbitrary-precision arithmetic (``mp``)
* Arbitrary-precision interval arithmetic (``iv``)
* Double-precision arithmetic using Python's builtin ``float`` and ``complex`` types (``fp``)
.. note::
Using global context is not thread-safe, create instead
local contexts with e.g. :class:`~mpmath.MPContext`.
Most global functions in the global mpmath namespace are actually methods of the ``mp``
context. This fact is usually transparent to the user, but sometimes shows up in the
form of an initial parameter called "ctx" visible in the help for the function::
>>> import mpmath
>>> help(mpmath.fsum)
Help on method fsum in module mpmath.ctx_mp_python:
<BLANKLINE>
fsum(terms, absolute=False, squared=False) method of mpmath.ctx_mp.MPContext instance
Calculates a sum containing a finite number of terms (for infinite
series, see :func:`~mpmath.nsum`). The terms will be converted to
...
The following operations are equivalent::
>>> mpmath.fsum([1,2,3])
mpf('6.0')
>>> mpmath.mp.fsum([1,2,3])
mpf('6.0')
The corresponding operation using the ``fp`` context::
>>> mpmath.fp.fsum([1,2,3])
6.0
Common interface
----------------
``ctx.mpf`` creates a real number::
>>> from mpmath import mp, fp
>>> mp.mpf(3)
mpf('3.0')
>>> fp.mpf(3)
3.0
``ctx.mpc`` creates a complex number::
>>> mp.mpc(2,3)
mpc(real='2.0', imag='3.0')
>>> fp.mpc(2,3)
(2+3j)
``ctx.matrix`` creates a matrix::
>>> mp.matrix([[1,0],[0,1]])
matrix(
[['1.0', '0.0'],
['0.0', '1.0']])
>>> _[0,0]
mpf('1.0')
>>> fp.matrix([[1,0],[0,1]])
matrix(
[['1.0', '0.0'],
['0.0', '1.0']])
>>> _[0,0]
1.0
``ctx.prec`` holds the current precision (in bits)::
>>> mp.prec
53
>>> fp.prec
53
``ctx.dps`` holds the current precision (in digits)::
>>> mp.dps
15
>>> fp.dps
15
``ctx.pretty`` controls whether objects should be pretty-printed automatically by :func:`repr`. Pretty-printing for ``mp`` numbers is disabled by default so that they can clearly be distinguished from Python numbers and so that ``eval(repr(x)) == x`` works::
>>> mp.mpf(3)
mpf('3.0')
>>> mpf = mp.mpf
>>> eval(repr(mp.mpf(3)))
mpf('3.0')
>>> mp.pretty = True
>>> mp.mpf(3)
3.0
>>> fp.matrix([[1,0],[0,1]])
matrix(
[['1.0', '0.0'],
['0.0', '1.0']])
>>> fp.pretty = True
>>> fp.matrix([[1,0],[0,1]])
[1.0 0.0]
[0.0 1.0]
>>> fp.pretty = False
Arbitrary-precision floating-point (``mp``)
---------------------------------------------
The ``mp`` context is what most users probably want to use most of the time, as it supports the most functions, is most well-tested, and is implemented with a high level of optimization. Nearly all examples in this documentation use ``mp`` functions.
See :doc:`basics` for a description of basic usage.
.. autoclass:: mpmath.MPContext
Local contexts, created on demand, could be used just as the global ``mp``:
>>> from mpmath import MPContext
>>> ctx = MPContext()
>>> ctx.sin(1)
mpf('0.8414709848078965')
>>> ctx.prec = 113
>>> ctx.sin(1)
mpf('0.841470984807896506652502321630298954')
Arbitrary-precision interval arithmetic (``iv``)
------------------------------------------------
The ``iv.mpf`` type represents a closed interval `[a,b]`; that is, the set `\{x : a \le x \le b\}`, where `a` and `b` are arbitrary-precision floating-point values, possibly `\pm \infty`. The ``iv.mpc`` type represents a rectangular complex interval `[a,b] + [c,d]i`; that is, the set `\{z = x+iy : a \le x \le b \land c \le y \le d\}`.
Interval arithmetic provides rigorous error tracking. If `f` is a mathematical function and `\hat f` is its interval arithmetic version, then the basic guarantee of interval arithmetic is that `f(v) \subseteq \hat f(v)` for any input interval `v`. Put differently, if an interval represents the known uncertainty for a fixed number, any sequence of interval operations will produce an interval that contains what would be the result of applying the same sequence of operations to the exact number. The principal drawbacks of interval arithmetic are speed (``iv`` arithmetic is typically at least two times slower than ``mp`` arithmetic) and that it sometimes provides far too pessimistic bounds.
.. note ::
The support for interval arithmetic in mpmath is still experimental, and many functions
do not yet properly support intervals. Please use this feature with caution.
Intervals can be created from single numbers (treated as zero-width intervals) or pairs of endpoint numbers. Strings are treated as exact decimal numbers. Note that a Python float like ``0.1`` generally does not represent the same number as its literal; use ``'0.1'`` instead::
>>> from mpmath import iv
>>> iv.mpf(3)
mpi('3.0', '3.0')
>>> print(iv.mpf(3))
[3.0, 3.0]
>>> iv.pretty = True
>>> iv.mpf([2,3])
[2.0, 3.0]
>>> iv.mpf(0.1) # probably not intended
[0.10000000000000000555, 0.10000000000000000555]
>>> iv.mpf('0.1') # good, gives a containing interval
[0.099999999999999991673, 0.10000000000000000555]
>>> iv.mpf(['0.1', '0.2'])
[0.099999999999999991673, 0.2000000000000000111]
The fact that ``'0.1'`` results in an interval of nonzero width indicates that 1/10 cannot be represented using binary floating-point numbers at this precision level (in fact, it cannot be represented exactly at any precision).
Intervals may be infinite or half-infinite::
>>> print(1 / iv.mpf([2, 'inf']))
[0.0, 0.5]
The equality testing operators ``==`` and ``!=`` check whether their operands
are identical as intervals; that is, have the same endpoints. The ordering
operators ``< <= > >=`` permit inequality testing using triple-valued logic: a
guaranteed inequality returns ``True`` or ``False`` while an indeterminate
inequality raises :exc:`ValueError`::
>>> iv.mpf([1,2]) == iv.mpf([1,2])
True
>>> iv.mpf([1,2]) != iv.mpf([1,2])
False
>>> iv.mpf([1,2]) <= 2
True
>>> iv.mpf([1,2]) > 0
True
>>> iv.mpf([1,2]) < 1
False
>>> iv.mpf([1,2]) < 2
Traceback (most recent call last):
...
ValueError
>>> iv.mpf([2,2]) < 2
False
>>> iv.mpf([1,2]) <= iv.mpf([2,3])
True
>>> iv.mpf([1,2]) < iv.mpf([2,3])
Traceback (most recent call last):
...
ValueError
>>> iv.mpf([1,2]) < iv.mpf([-1,0])
False
The ``in`` operator tests whether a number or interval is contained in another interval::
>>> iv.mpf([0,2]) in iv.mpf([0,10])
True
>>> 3 in iv.mpf(['-inf', 0])
False
Intervals have the properties ``.a``, ``.b`` (endpoints), ``.mid``, and ``.delta`` (width)::
>>> x = iv.mpf([2, 5])
>>> x.a
[2.0, 2.0]
>>> x.b
[5.0, 5.0]
>>> x.mid
[3.5, 3.5]
>>> x.delta
[3.0, 3.0]
Some transcendental functions are supported::
>>> iv.dps = 15
>>> mp.dps = 15
>>> iv.mpf([0.5,1.5]) ** iv.mpf([0.5, 1.5])
[0.35355339059327373086, 1.837117307087383633]
>>> iv.exp(0)
[1.0, 1.0]
>>> iv.exp(['-inf','inf'])
[0.0, inf]
>>>
>>> iv.exp(['-inf',0])
[0.0, 1.0]
>>> iv.exp([0,'inf'])
[1.0, inf]
>>> iv.exp([0,1])
[1.0, 2.7182818284590455349]
>>>
>>> iv.log(1)
[0.0, 0.0]
>>> iv.log([0,1])
[-inf, 0.0]
>>> iv.log([0,'inf'])
[-inf, inf]
>>> iv.log(2)
[0.69314718055994528623, 0.69314718055994539725]
>>>
>>> iv.sin([100,'inf'])
[-1.0, 1.0]
>>> iv.cos(['-0.1','0.1'])
[0.99500416527802570954, 1.0]
Interval arithmetic is useful for proving inequalities involving irrational numbers.
Naive use of ``mp`` arithmetic may result in wrong conclusions, such as the following::
>>> mp.dps = 25
>>> x = mp.exp(mp.pi*mp.sqrt(163))
>>> y = mp.mpf(640320**3+744)
>>> print(x)
262537412640768744.0000001
>>> print(y)
262537412640768744.0
>>> x > y
True
But the correct result is `e^{\pi \sqrt{163}} < 262537412640768744`, as can be
seen by increasing the precision::
>>> mp.dps = 50
>>> print(mp.exp(mp.pi*mp.sqrt(163)))
262537412640768743.99999999999925007259719818568888
With interval arithmetic, the comparison raises :exc:`ValueError` until the
precision is large enough for `x-y` to have a definite sign::
>>> iv.dps = 15
>>> iv.exp(iv.pi*iv.sqrt(163)) > (640320**3+744)
Traceback (most recent call last):
...
ValueError
>>> iv.dps = 30
>>> iv.exp(iv.pi*iv.sqrt(163)) > (640320**3+744)
Traceback (most recent call last):
...
ValueError
>>> iv.dps = 60
>>> iv.exp(iv.pi*iv.sqrt(163)) > (640320**3+744)
False
>>> iv.dps = 15
Fast low-precision arithmetic (``fp``)
---------------------------------------------
Although mpmath is generally designed for arbitrary-precision arithmetic, many of the high-level algorithms work perfectly well with ordinary Python ``float`` and ``complex`` numbers, which use hardware double precision (on most systems, this corresponds to 53 bits of precision). Whereas the global functions (which are methods of the ``mp`` object) always convert inputs to mpmath numbers, the ``fp`` object instead converts them to ``float`` or ``complex``, and in some cases employs basic functions optimized for double precision. When large amounts of function evaluations (numerical integration, plotting, etc) are required, and when ``fp`` arithmetic provides sufficient accuracy, this can give a significant speedup over ``mp`` arithmetic.
To take advantage of this feature, simply use the ``fp`` prefix, i.e. write ``fp.func`` instead of ``func`` or ``mp.func``::
>>> u = fp.erfc(0.5)
>>> print(u)
0.4795001221869535
>>> type(u)
<class 'float'>
>>> mp.dps = 16
>>> print(mp.erfc(0.5))
0.4795001221869535
>>> fp.matrix([[1,2],[3,4]]) ** 2
matrix(
[['7.0', '10.0'],
['15.0', '22.0']])
>>>
>>> type(_[0,0])
<class 'float'>
>>> print(fp.quad(fp.sin, [0, fp.pi])) # numerical integration
2.0
The ``fp`` context wraps Python's ``math`` and ``cmath`` modules for elementary functions. It supports both real and complex numbers and automatically generates complex results for real inputs (``math`` raises an exception)::
>>> fp.sqrt(5)
2.23606797749979
>>> fp.sqrt(-5)
2.23606797749979j
>>> fp.sin(10)
-0.5440211108893698
>>> fp.power(-1, 0.25)
(0.7071067811865476+0.7071067811865475j)
>>> (-1) ** 0.25
(0.7071067811865476+0.7071067811865475j)
The ``prec`` and ``dps`` attributes can be changed (for interface compatibility with the ``mp`` context) but this has no effect::
>>> fp.prec
53
>>> fp.dps
15
>>> fp.prec = 80
>>> fp.prec
53
>>> fp.dps
15
Due to intermediate rounding and cancellation errors, results computed with ``fp`` arithmetic may be much less accurate than those computed with ``mp`` using an equivalent precision (``mp.prec = 53``), since the latter often uses increased internal precision. The accuracy is highly problem-dependent: for some functions, ``fp`` almost always gives 14-15 correct digits; for others, results can be accurate to only 2-3 digits or even completely wrong. The recommended use for ``fp`` is therefore to speed up large-scale computations where accuracy can be verified in advance on a subset of the input set, or where results can be verified afterwards.
Beware that the ``fp`` context has signed zero, that can be used to distinguish
different sides of branch cuts. For example, ``fp.mpc(-1, -0.0)`` is treated
as though it lies *below* the branch cut for :func:`~mpmath.sqrt()`::
>>> fp.sqrt(fp.mpc(-1, -0.0))
-1j
>>> fp.sqrt(fp.mpc(-1, -1e-10))
(5e-11-1j)
But an argument of ``fp.mpc(-1, 0.0)`` is treated as though it lies *above* the
branch cut::
>>> fp.sqrt(fp.mpc(-1, +0.0))
1j
>>> fp.sqrt(fp.mpc(-1, +1e-10))
(5e-11+1j)
While near the branch cut, for small but nonzero deviations in components
results agreed with the ``mp`` contexts::
>>> fp.mpc(mp.sqrt(mp.mpc(-1, -1e-10)))
(5e-11-1j)
>>> fp.mpc(mp.sqrt(mp.mpc(-1, +1e-10)))
(5e-11+1j)
one has no signed zeros and allows to specify result *on the branch cut*
(nonpositive part of the real axis in this example)::
>>> fp.mpc(mp.sqrt(mp.mpc(-1, 0)))
1j
>>> fp.mpc(mp.sqrt(-1))
1j
Here it's continuous from the above of the :func:`~mpmath.sqrt()` branch
cut (from ``0`` along the negative real axis to the negative infinity).
+108
View File
@@ -0,0 +1,108 @@
Bessel functions and related functions
--------------------------------------
The functions in this section arise as solutions to various differential
equations in physics, typically describing wavelike oscillatory behavior or a
combination of oscillation and exponential decay or growth. Mathematically,
they are special cases of the confluent hypergeometric functions `\,_0F_1`,
`\,_1F_1` and `\,_1F_2` (see :doc:`hypergeometric`).
Bessel functions
................
.. autofunction:: mpmath.besselj
.. autofunction:: mpmath.j0
.. autofunction:: mpmath.j1
.. autofunction:: mpmath.bessely
.. autofunction:: mpmath.besseli
.. autofunction:: mpmath.besselk
Bessel function zeros
.....................
.. autofunction:: mpmath.besseljzero
.. autofunction:: mpmath.besselyzero
Hankel functions
................
.. autofunction:: mpmath.hankel1
.. autofunction:: mpmath.hankel2
Spherical Bessel functions
..........................
.. autofunction:: mpmath.spherical_jn
.. autofunction:: mpmath.spherical_yn
.. autofunction:: mpmath.spherical_in
.. autofunction:: mpmath.spherical_kn
Kelvin functions
................
.. autofunction:: mpmath.ber
.. autofunction:: mpmath.bei
.. autofunction:: mpmath.ker
.. autofunction:: mpmath.kei
Struve functions
................
.. autofunction:: mpmath.struveh
.. autofunction:: mpmath.struvel
Anger-Weber functions
.....................
.. autofunction:: mpmath.angerj
.. autofunction:: mpmath.webere
Lommel functions
................
.. autofunction:: mpmath.lommels1
.. autofunction:: mpmath.lommels2
Airy and Scorer functions
.........................
.. autofunction:: mpmath.airyai
.. autofunction:: mpmath.airybi
.. autofunction:: mpmath.airyaizero
.. autofunction:: mpmath.airybizero
.. autofunction:: mpmath.scorergi
.. autofunction:: mpmath.scorerhi
Coulomb wave functions
......................
.. autofunction:: mpmath.coulombf
.. autofunction:: mpmath.coulombg
.. autofunction:: mpmath.coulombc
Confluent U and Whittaker functions
...................................
.. autofunction:: mpmath.hyperu(a, b, z)
.. autofunction:: mpmath.whitm(k,m,z)
.. autofunction:: mpmath.whitw(k,m,z)
Parabolic cylinder functions
............................
.. autofunction:: mpmath.pcfd
.. autofunction:: mpmath.pcfu
.. autofunction:: mpmath.pcfv
.. autofunction:: mpmath.pcfw
+45
View File
@@ -0,0 +1,45 @@
Mathematical constants
----------------------
Mpmath supports arbitrary-precision computation of various common (and less
common) mathematical constants. These constants are implemented as lazy
objects that can evaluate to any precision. Whenever the objects are used as
function arguments or as operands in arithmetic operations, they automagically
evaluate to the current working precision. A lazy number can be converted to a
regular ``mpf`` using the unary ``+`` operator, or by calling it as a
function::
>>> from mpmath import pi, mp
>>> pi
<pi: 3.14159~>
>>> 2*pi
mpf('6.2831853071795862')
>>> +pi
mpf('3.1415926535897931')
>>> pi()
mpf('3.1415926535897931')
>>> mp.dps = 40
>>> pi
<pi: 3.14159~>
>>> 2*pi
mpf('6.28318530717958647692528676655900576839434')
>>> +pi
mpf('3.14159265358979323846264338327950288419717')
>>> pi()
mpf('3.14159265358979323846264338327950288419717')
The predefined objects ``j`` (imaginary unit), ``inf`` (positive infinity) and
``nan`` (not-a-number) are shortcuts to ``mpc`` and ``mpf`` instances with
these fixed values.
.. autofunction:: mpmath.mp.pi
.. autoattribute:: mpmath.mp.degree
.. autoattribute:: mpmath.mp.e
.. autoattribute:: mpmath.mp.phi
.. autofunction:: mpmath.mp.euler
.. autoattribute:: mpmath.mp.catalan
.. autoattribute:: mpmath.mp.apery
.. autoattribute:: mpmath.mp.khinchin
.. autoattribute:: mpmath.mp.glaisher
.. autoattribute:: mpmath.mp.mertens
.. autoattribute:: mpmath.mp.twinprime
+65
View File
@@ -0,0 +1,65 @@
Elliptic functions
------------------
.. automodule:: mpmath.functions.elliptic
:no-index:
Elliptic arguments
..................
.. autofunction:: mpmath.qfrom
.. autofunction:: mpmath.qbarfrom
.. autofunction:: mpmath.mfrom
.. autofunction:: mpmath.kfrom
.. autofunction:: mpmath.taufrom
Legendre elliptic integrals
...........................
.. autofunction:: mpmath.ellipk
.. autofunction:: mpmath.ellipf
.. autofunction:: mpmath.ellipe
.. autofunction:: mpmath.ellippi
Carlson symmetric elliptic integrals
....................................
.. autofunction:: mpmath.elliprf
.. autofunction:: mpmath.elliprc
.. autofunction:: mpmath.elliprj
.. autofunction:: mpmath.elliprd
.. autofunction:: mpmath.elliprg
Jacobi theta functions
......................
.. autofunction:: mpmath.jtheta
Jacobi elliptic functions
.........................
.. autofunction:: mpmath.ellipfun
Weierstrass elliptic functions
..............................
.. autofunction:: mpmath.weierinvariants
.. autofunction:: mpmath.weierhalfperiods
.. autofunction:: mpmath.weierp
.. autofunction:: mpmath.weierpprime
.. autofunction:: mpmath.weiersigma
.. autofunction:: mpmath.weierzeta
.. autofunction:: mpmath.weierpinv
Modular functions
.................
.. autofunction:: mpmath.eta
.. autofunction:: mpmath.kleinj
+70
View File
@@ -0,0 +1,70 @@
Exponential integrals and error functions
-----------------------------------------
Exponential integrals give closed-form solutions to a large class of commonly
occurring transcendental integrals that cannot be evaluated using elementary
functions. Integrals of this type include those with an integrand of the form
`t^a e^{t}` or `e^{-x^2}`, the latter giving rise to the Gaussian (or normal)
probability distribution.
The most general function in this section is the incomplete gamma function, to
which all others can be reduced. The incomplete gamma function, in turn, can
be expressed using hypergeometric functions (see :doc:`hypergeometric`).
Incomplete gamma functions
..........................
.. autofunction:: mpmath.gammainc
.. autofunction:: mpmath.lower_gamma
.. autofunction:: mpmath.upper_gamma
Exponential integrals
.....................
.. autofunction:: mpmath.ei
.. autofunction:: mpmath.e1
.. autofunction:: mpmath.expint
Logarithmic integral
....................
.. autofunction:: mpmath.li
Trigonometric integrals
.......................
.. autofunction:: mpmath.ci
.. autofunction:: mpmath.si
Hyperbolic integrals
....................
.. autofunction:: mpmath.chi
.. autofunction:: mpmath.shi
Error functions
...............
.. autofunction:: mpmath.erf
.. autofunction:: mpmath.erfc
.. autofunction:: mpmath.erfi
.. autofunction:: mpmath.erfinv
The normal distribution
.......................
.. autofunction:: mpmath.npdf
.. autofunction:: mpmath.ncdf
Fresnel integrals
.................
.. autofunction:: mpmath.fresnels
.. autofunction:: mpmath.fresnelc
+79
View File
@@ -0,0 +1,79 @@
Factorials and gamma functions
------------------------------
Factorials and factorial-like sums and products are basic tools of
combinatorics and number theory. Much like the exponential function is
fundamental to differential equations and analysis in general, the factorial
function (and its extension to complex numbers, the gamma function) is
fundamental to difference equations and functional equations.
A large selection of factorial-like functions is implemented in mpmath. All
functions support complex arguments, and arguments may be arbitrarily large.
Results are numerical approximations, so to compute *exact* values a high
enough precision must be set manually::
>>> from mpmath import mp, fac
>>> mp.dps = 15
>>> mp.pretty = True
>>> fac(100)
9.33262154439442e+157
>>> print(int(_)) # most digits are wrong
93326215443944150965646704795953882578400970373184098831012889540582227238570431295066113089288327277825849664006524270554535976289719382852181865895959724032
>>> mp.dps = 160
>>> fac(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000.0
The gamma and polygamma functions are closely related to :doc:`zeta`. See also
:doc:`qfunctions` for q-analogs of factorial-like functions.
Factorials
..........
.. autofunction:: mpmath.factorial
.. autofunction:: mpmath.fac2
Binomial coefficients
.....................
.. autofunction:: mpmath.binomial
Gamma function
..............
.. autofunction:: mpmath.gamma
.. autofunction:: mpmath.rgamma
.. autofunction:: mpmath.gammaprod
.. autofunction:: mpmath.loggamma
Rising and falling factorials
.............................
.. autofunction:: mpmath.rf
.. autofunction:: mpmath.ff
Beta function
.............
.. autofunction:: mpmath.beta
.. autofunction:: mpmath.betainc
Super- and hyperfactorials
..........................
.. autofunction:: mpmath.superfac
.. autofunction:: mpmath.hyperfac
.. autofunction:: mpmath.barnesg
Polygamma functions and harmonic numbers
........................................
.. autofunction:: mpmath.psi
.. autofunction:: mpmath.digamma
.. autofunction:: mpmath.harmonic
+23
View File
@@ -0,0 +1,23 @@
Hyperbolic functions
--------------------
Hyperbolic functions
....................
.. autofunction:: mpmath.cosh
.. autofunction:: mpmath.sinh
.. autofunction:: mpmath.tanh
.. autofunction:: mpmath.sech
.. autofunction:: mpmath.csch
.. autofunction:: mpmath.coth
Inverse hyperbolic functions
............................
.. autofunction:: mpmath.acosh
.. autofunction:: mpmath.asinh
.. autofunction:: mpmath.atanh
.. autofunction:: mpmath.asech
.. autofunction:: mpmath.acsch
.. autofunction:: mpmath.acoth
+74
View File
@@ -0,0 +1,74 @@
Hypergeometric functions
------------------------
The functions listed in :doc:`expintegrals`, :doc:`bessel` and
:doc:`orthogonal`, and many other functions as well, are merely particular
instances of the generalized hypergeometric function `\,_pF_q`. The functions
listed in the following section enable efficient direct evaluation of the
underlying hypergeometric series, as well as linear combinations, limits with
respect to parameters, and analytic continuations thereof. Extensions to
twodimensional series are also provided. See also the basic or q-analog of the
hypergeometric series in :doc:`qfunctions`.
For convenience, most of the hypergeometric series of low order are provided as
standalone functions. They can equivalently be evaluated using
:func:`~mpmath.hyper`. As will be demonstrated in the respective docstrings,
all the ``hyp#f#`` functions implement analytic continuations and/or asymptotic
expansions with respect to the argument `z`, thereby permitting evaluation for
`z` anywhere in the complex plane. Functions of higher degree can be computed
via :func:`~mpmath.hyper`, but generally only in rapidly convergent instances.
Most hypergeometric and hypergeometric-derived functions accept optional
keyword arguments to specify options for :func:`~mpmath.hypercomb` or
:func:`~mpmath.hyper`. Some useful options are *maxprec*, *maxterms*,
*zeroprec*, *accurate_small*, *hmag*, *force_series*, *asymp_tol* and
*eliminate*. These options give control over what to do in case of slow
convergence, extreme loss of accuracy or evaluation at zeros (these two cases
cannot generally be distinguished from each other automatically), and singular
parameter combinations.
Common hypergeometric series
............................
.. autofunction:: mpmath.hyp0f1
.. autofunction:: mpmath.hyp1f1
.. autofunction:: mpmath.hyp1f2
.. autofunction:: mpmath.hyp2f0
.. autofunction:: mpmath.hyp2f1
.. autofunction:: mpmath.hyp2f2
.. autofunction:: mpmath.hyp2f3
.. autofunction:: mpmath.hyp3f2
Generalized hypergeometric functions
....................................
.. autofunction:: mpmath.hyper
.. autofunction:: mpmath.hypercomb
Meijer G-function
.................
.. autofunction:: mpmath.meijerg
Fox H-function
.................
.. autofunction:: mpmath.foxh
Bilateral hypergeometric series
...............................
.. autofunction:: mpmath.bihyper
Hypergeometric functions of two variables
.........................................
.. autofunction:: mpmath.hyper2d
.. autofunction:: mpmath.appellf1
.. autofunction:: mpmath.appellf2
.. autofunction:: mpmath.appellf3
.. autofunction:: mpmath.appellf4
+22
View File
@@ -0,0 +1,22 @@
Mathematical functions
======================
Mpmath implements the standard functions from Python's ``math`` and ``cmath`` modules, for both real and complex numbers and with arbitrary precision. Many other functions are also available in mpmath, including commonly-used variants of standard functions (such as the alternative trigonometric functions sec, csc, cot), but also a large number of "special functions" such as the gamma function, the Riemann zeta function, error functions, Bessel functions, etc.
.. toctree::
:maxdepth: 2
constants
powers
trigonometric
hyperbolic
signals
gamma
expintegrals
bessel
orthogonal
hypergeometric
elliptic
zeta
numtheory
qfunctions
+58
View File
@@ -0,0 +1,58 @@
Number-theoretical, combinatorial and integer functions
-------------------------------------------------------
For factorial-type functions, including binomial coefficients, double
factorials, etc, see the separate section :doc:`gamma`.
Fibonacci numbers
.................
.. autofunction:: mpmath.fibonacci
Bernoulli numbers and polynomials
.................................
.. autofunction:: mpmath.bernoulli
.. autofunction:: mpmath.bernfrac
.. autofunction:: mpmath.bernpoly
Euler numbers and polynomials
.............................
.. autofunction:: mpmath.eulernum
.. autofunction:: mpmath.eulerpoly
Bell numbers and polynomials
............................
.. autofunction:: mpmath.bell
Stirling numbers
................
.. autofunction:: mpmath.stirling1
.. autofunction:: mpmath.stirling2
Prime counting functions
........................
.. autofunction:: mpmath.primepi
.. autofunction:: mpmath.primepi2
.. autofunction:: mpmath.riemannr
Cyclotomic polynomials
......................
.. autofunction:: mpmath.cyclotomic
Arithmetic functions
......................
.. autofunction:: mpmath.mangoldt
+77
View File
@@ -0,0 +1,77 @@
Orthogonal polynomials
----------------------
An orthogonal polynomial sequence is a sequence of polynomials `P_0(x), P_1(x),
\ldots` of degree `0, 1, \ldots`, which are mutually orthogonal in the sense
that
.. math ::
\int_S P_n(x) P_m(x) w(x) dx =
\begin{cases}
c_n \ne 0 & \text{if $m = n$} \\
0 & \text{if $m \ne n$}
\end{cases}
where `S` is some domain (e.g. an interval `[a,b] \in \mathbb{R}`) and `w(x)`
is a fixed *weight function*. A sequence of orthogonal polynomials is
determined completely by `w`, `S`, and a normalization convention (e.g. `c_n =
1`). Applications of orthogonal polynomials include function approximation and
solution of differential equations.
Orthogonal polynomials are sometimes defined using the differential equations
they satisfy (as functions of `x`) or the recurrence relations they satisfy
with respect to the order `n`. Other ways of defining orthogonal polynomials
include differentiation formulas and generating functions. The standard
orthogonal polynomials can also be represented as hypergeometric series (see
:doc:`hypergeometric`), more specifically using the Gauss hypergeometric
function `\,_2F_1` in most cases. The following functions are generally
implemented using hypergeometric functions since this is computationally
efficient and easily generalizes.
For more information, see the `Wikipedia article on orthogonal polynomials
<http://en.wikipedia.org/wiki/Orthogonal_polynomials>`_.
Legendre functions
..................
.. autofunction:: mpmath.legendre
.. autofunction:: mpmath.legenp
.. autofunction:: mpmath.legenq
Chebyshev polynomials
.....................
.. autofunction:: mpmath.chebyt
.. autofunction:: mpmath.chebyu
Jacobi polynomials
..................
.. autofunction:: mpmath.jacobi
Gegenbauer polynomials
......................
.. autofunction:: mpmath.gegenbauer
Hermite polynomials
...................
.. autofunction:: mpmath.hermite
Laguerre polynomials
....................
.. autofunction:: mpmath.laguerre
Spherical harmonics
...................
.. autofunction:: mpmath.spherharm
+45
View File
@@ -0,0 +1,45 @@
Powers and logarithms
---------------------
Nth roots
.........
.. autofunction:: mpmath.sqrt
.. autofunction:: mpmath.hypot
.. autofunction:: mpmath.cbrt
.. autofunction:: mpmath.root
.. autofunction:: mpmath.unitroots
Exponentiation
..............
.. autofunction:: mpmath.exp
.. autofunction:: mpmath.exp2
.. autofunction:: mpmath.power
.. autofunction:: mpmath.expj
.. autofunction:: mpmath.expjpi
.. autofunction:: mpmath.expm1(x)
.. autofunction:: mpmath.powm1(x, y)
Logarithms
..........
.. autofunction:: mpmath.log
.. autofunction:: mpmath.ln
.. autofunction:: mpmath.log2
.. autofunction:: mpmath.log10
.. autofunction:: mpmath.log1p(x)
Lambert W function
..................
.. autofunction:: mpmath.lambertw
Arithmetic-geometric mean
.........................
.. autofunction:: mpmath.agm
+20
View File
@@ -0,0 +1,20 @@
q-functions
-----------
q-Pochhammer symbol
...................
.. autofunction:: mpmath.qp
q-gamma and factorial
.....................
.. autofunction:: mpmath.qgamma
.. autofunction:: mpmath.qfac
Hypergeometric q-series
.......................
.. autofunction:: mpmath.qhyper
+34
View File
@@ -0,0 +1,34 @@
Signal functions
----------------
The functions in this section describe non-sinusoidal waveforms, which are
often used in signal processing and electronics.
Square wave signal
..................
.. autofunction:: mpmath.squarew
Triangle wave signal
....................
.. autofunction:: mpmath.trianglew
Sawtooth wave signal
....................
.. autofunction:: mpmath.sawtoothw
Unit triangle signal
....................
.. autofunction:: mpmath.unit_triangle
Sigmoid wave signal
.....................
.. autofunction:: mpmath.sigmoid
+62
View File
@@ -0,0 +1,62 @@
Trigonometric functions
-----------------------
Except where otherwise noted, the trigonometric functions take a radian angle
as input and the inverse trigonometric functions return radian angles.
The ordinary trigonometric functions are single-valued functions defined
everywhere in the complex plane (except at the poles of tan, sec, csc, and
cot). They are defined generally via the exponential function, e.g.
.. math ::
\cos(x) = \frac{e^{ix} + e^{-ix}}{2}.
The inverse trigonometric functions are multivalued, thus requiring branch
cuts, and are generally real-valued only on a part of the real line.
Definitions and branch cuts are given in the documentation of each function.
The branch cut conventions used by mpmath are essentially the same as those
found in most standard mathematical software, such as Mathematica and Python's
own ``cmath`` libary.
Degree-radian conversion
........................
.. autofunction:: mpmath.degrees
.. autofunction:: mpmath.radians
Trigonometric functions
.......................
.. autofunction:: mpmath.cos
.. autofunction:: mpmath.sin
.. autofunction:: mpmath.tan
.. autofunction:: mpmath.sec
.. autofunction:: mpmath.csc
.. autofunction:: mpmath.cot
Trigonometric functions with modified argument
..............................................
.. autofunction:: mpmath.cospi
.. autofunction:: mpmath.sinpi
Inverse trigonometric functions
...............................
.. autofunction:: mpmath.acos
.. autofunction:: mpmath.asin
.. autofunction:: mpmath.atan
.. autofunction:: mpmath.atan2
.. autofunction:: mpmath.asec
.. autofunction:: mpmath.acsc
.. autofunction:: mpmath.acot
Sinc function
.............
.. autofunction:: mpmath.sinc
.. autofunction:: mpmath.sincpi
+60
View File
@@ -0,0 +1,60 @@
Zeta functions, L-series and polylogarithms
-------------------------------------------
This section includes the Riemann zeta functions and associated functions
pertaining to analytic number theory.
Riemann and Hurwitz zeta functions
..................................
.. autofunction:: mpmath.zeta
Dirichlet L-series
..................
.. autofunction:: mpmath.altzeta
.. autofunction:: mpmath.dirichlet
Stieltjes constants
...................
.. autofunction:: mpmath.stieltjes
Zeta function zeros
...................
These functions are used for the study of the Riemann zeta function in the
critical strip.
.. autofunction:: mpmath.zetazero
.. autofunction:: mpmath.nzeros
.. autofunction:: mpmath.siegelz
.. autofunction:: mpmath.siegeltheta
.. autofunction:: mpmath.grampoint
.. autofunction:: mpmath.backlunds
Lerch transcendent
..................
.. autofunction:: mpmath.lerchphi
Polylogarithms and Clausen functions
....................................
.. autofunction:: mpmath.polylog
.. autofunction:: mpmath.clsin
.. autofunction:: mpmath.clcos
.. autofunction:: mpmath.polyexp
Zeta function variants
......................
.. autofunction:: mpmath.primezeta
.. autofunction:: mpmath.secondzeta
+240
View File
@@ -0,0 +1,240 @@
Utility functions
===============================================
This page lists functions that perform basic operations
on numbers or aid general programming.
Conversion and printing
-----------------------
:func:`~mpmath.mpmathify` / ``convert()``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.mpmathify
:func:`~mpmath.nstr`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.nstr
:func:`~mpmath.nprint`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.nprint
:func:`mpmath.mpf.__format__`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.mpf.__format__
:func:`mpmath.mpc.__format__`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.mpc.__format__
Arithmetic operations
---------------------
See also :func:`mpmath.sqrt`, :func:`mpmath.exp` etc., listed
in :doc:`functions/powers`
:func:`~mpmath.fadd`
^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fadd
:func:`~mpmath.fsub`
^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fsub
:func:`~mpmath.fneg`
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fneg
:func:`~mpmath.fmul`
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fmul
:func:`~mpmath.fdiv`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fdiv
:func:`~mpmath.fmod`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fmod
:func:`~mpmath.fsum`
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fsum
:func:`~mpmath.fprod`
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fprod
:func:`~mpmath.fdot`
^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fdot
Complex components
------------------
:func:`~mpmath.fabs`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fabs
:func:`~mpmath.sign`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.sign
:func:`~mpmath.re`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.re
:func:`~mpmath.im`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.im
:func:`~mpmath.arg`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.arg
:func:`~mpmath.conj`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.conj
:func:`~mpmath.polar`
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.polar
:func:`~mpmath.rect`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.rect
Integer and fractional parts
-----------------------------
:func:`~mpmath.floor`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.floor
:func:`~mpmath.ceil`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.ceil
:func:`~mpmath.nint`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.nint
:func:`~mpmath.frac`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.frac
Tolerances and approximate comparisons
--------------------------------------
:func:`~mpmath.chop`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.chop
:func:`~mpmath.almosteq`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.almosteq
Properties of numbers
-------------------------------------
:func:`~mpmath.isinf`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.isinf
:func:`~mpmath.isnan`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.isnan
:func:`~mpmath.isnormal`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.isnormal
:func:`~mpmath.isfinite`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.isfinite
:func:`~mpmath.isint`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.isint
:func:`~mpmath.ldexp`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.ldexp
:func:`~mpmath.frexp`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.frexp
:func:`~mpmath.mag`
^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.mag
:func:`~mpmath.nint_distance`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.nint_distance
.. :func:`~mpmath.absmin`
.. ^^^^^^^^^^^^^^^^^^^^^^^^
.. .. autofunction:: mpmath.absmin(x)
.. .. autofunction:: mpmath.absmax(x)
Number generation
-----------------
:func:`~mpmath.fraction`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.fraction
:func:`~mpmath.rand`
^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.rand
:func:`~mpmath.arange`
^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.arange
:func:`~mpmath.linspace`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.linspace
Precision management
--------------------
:func:`~mpmath.autoprec`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.autoprec
:func:`~mpmath.workprec`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.workprec
:func:`~mpmath.workdps`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.workdps
:func:`~mpmath.extraprec`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.extraprec
:func:`~mpmath.extradps`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.extradps
Performance and debugging
------------------------------------
:func:`~mpmath.memoize`
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.memoize
:func:`~mpmath.maxcalls`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.maxcalls
:func:`~mpmath.monitor`
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.monitor
:func:`~mpmath.timing`
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.timing
+2
View File
@@ -0,0 +1,2 @@
Index
=====
+31
View File
@@ -0,0 +1,31 @@
Number identification
=====================
Most function in mpmath are concerned with producing approximations from exact mathematical formulas. It is also useful to consider the inverse problem: given only a decimal approximation for a number, such as 0.7320508075688772935274463, is it possible to find an exact formula?
Subject to certain restrictions, such "reverse engineering" is indeed possible thanks to the existence of *integer relation algorithms*. Mpmath implements the PSLQ algorithm (developed by H. Ferguson), which is one such algorithm.
Automated number recognition based on PSLQ is not a silver bullet. Any occurring transcendental constants (`\pi`, `e`, etc) must be guessed by the user, and the relation between those constants in the formula must be linear (such as `x = 3 \pi + 4 e`). More complex formulas can be found by combining PSLQ with functional transformations; however, this is only feasible to a limited extent since the computation time grows exponentially with the number of operations that need to be combined.
The number identification facilities in mpmath are inspired by the `Inverse Symbolic Calculator <http://wayback.cecm.sfu.ca/projects/ISC/ISCmain.html>`_ (ISC). The ISC is more powerful than mpmath, as it uses a lookup table of millions of precomputed constants (thereby mitigating the problem with exponential complexity).
Constant recognition
-----------------------------------
:func:`~mpmath.identify`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.identify
Algebraic identification
---------------------------------------
:func:`~mpmath.findpoly`
^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.findpoly
Integer relations (PSLQ)
----------------------------
:func:`~mpmath.pslq`
^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: mpmath.pslq
+55
View File
@@ -0,0 +1,55 @@
.. mpmath documentation master file, created by sphinx-quickstart on Fri Mar 28 13:50:14 2008.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to mpmath's documentation!
==================================
Mpmath is a Python library for arbitrary-precision floating-point arithmetic.
For general information about mpmath, see the project website https://mpmath.org/
These documentation pages include general information as well as docstring listing with extensive use of examples that can be run in the interactive Python interpreter. For quick access to the docstrings of individual functions, use the `index listing <genindex.html>`_, or type ``help(mpmath.function_name)`` in the Python interactive prompt.
Introduction
------------
.. toctree ::
:maxdepth: 2
setup
basics
Basic features
----------------
.. toctree ::
:maxdepth: 2
contexts
general
plotting
cli
Advanced mathematics
--------------------
On top of its support for arbitrary-precision arithmetic, mpmath
provides extensive support for transcendental functions, evaluation of sums, integrals, limits, roots, and so on.
.. toctree ::
:maxdepth: 2
functions/index
calculus/index
matrices
identification
End matter
----------
.. toctree ::
:maxdepth: 2
technical
references
genindex
+569
View File
@@ -0,0 +1,569 @@
Matrices
========
Creating matrices
-----------------
Basic methods
.............
Matrices in mpmath are implemented using dictionaries. Only non-zero values are
stored, so it is cheap to represent sparse matrices.
The most basic way to create one is to use the ``matrix`` class directly. You
can create an empty matrix specifying the dimensions::
>>> from mpmath import (matrix, ones, zeros, randmatrix, nprint, chop, iv,
... lu_solve, residual, fp, lu, diag, eye, eps, qr)
>>> matrix(2)
matrix(
[['0.0', '0.0'],
['0.0', '0.0']])
>>> matrix(2, 3)
matrix(
[['0.0', '0.0', '0.0'],
['0.0', '0.0', '0.0']])
Calling ``matrix`` with one dimension will create a square matrix.
To access the dimensions of a matrix, use the ``rows`` or ``cols`` keyword::
>>> A = matrix(3, 2)
>>> A
matrix(
[['0.0', '0.0'],
['0.0', '0.0'],
['0.0', '0.0']])
>>> A.rows
3
>>> A.cols
2
You can also change the dimension of an existing matrix. This will set the
new elements to 0. If the new dimension is smaller than before, the
concerning elements are discarded::
>>> A.rows = 2
>>> A
matrix(
[['0.0', '0.0'],
['0.0', '0.0']])
Internally ``convert`` is applied every time an element is set. This is
done using the syntax A[row,column], counting from 0::
>>> A = matrix(2)
>>> A[1,1] = 1 + 1j
>>> print(A)
[0.0 0.0]
[0.0 (1.0 + 1.0j)]
A more comfortable way to create a matrix lets you use nested lists::
>>> matrix([[1, 2], [3, 4]])
matrix(
[['1.0', '2.0'],
['3.0', '4.0']])
Advanced methods
................
Convenient functions are available for creating various standard matrices::
>>> zeros(2)
matrix(
[['0.0', '0.0'],
['0.0', '0.0']])
>>> ones(2)
matrix(
[['1.0', '1.0'],
['1.0', '1.0']])
>>> diag([1, 2, 3]) # diagonal matrix
matrix(
[['1.0', '0.0', '0.0'],
['0.0', '2.0', '0.0'],
['0.0', '0.0', '3.0']])
>>> eye(2) # identity matrix
matrix(
[['1.0', '0.0'],
['0.0', '1.0']])
You can even create random matrices::
>>> randmatrix(2) # doctest:+SKIP
matrix(
[['0.53491598236191806', '0.57195669543302752'],
['0.85589992269513615', '0.82444367501382143']])
Vectors
.......
Vectors may also be represented by the ``matrix`` class (with rows = 1 or cols = 1).
For vectors there are some things which make life easier. A column vector can
be created using a flat list, a row vectors using an almost flat nested list::
>>> matrix([1, 2, 3])
matrix(
[['1.0'],
['2.0'],
['3.0']])
>>> matrix([[1, 2, 3]])
matrix(
[['1.0', '2.0', '3.0']])
Optionally vectors can be accessed like lists, using only a single index::
>>> x = matrix([1, 2, 3])
>>> x[1]
mpf('2.0')
>>> x[1,0]
mpf('2.0')
Other
.....
Like you probably expected, matrices can be printed::
>>> print(randmatrix(3)) # doctest:+SKIP
[ 0.782963853573023 0.802057689719883 0.427895717335467]
[0.0541876859348597 0.708243266653103 0.615134039977379]
[ 0.856151514955773 0.544759264818486 0.686210904770947]
Use ``nstr`` or ``nprint`` to specify the number of digits to print::
>>> nprint(randmatrix(5), 3) # doctest:+SKIP
[2.07e-1 1.66e-1 5.06e-1 1.89e-1 8.29e-1]
[6.62e-1 6.55e-1 4.47e-1 4.82e-1 2.06e-2]
[4.33e-1 7.75e-1 6.93e-2 2.86e-1 5.71e-1]
[1.01e-1 2.53e-1 6.13e-1 3.32e-1 2.59e-1]
[1.56e-1 7.27e-2 6.05e-1 6.67e-2 2.79e-1]
As matrices are mutable, you will need to copy them sometimes::
>>> A = matrix(2)
>>> A
matrix(
[['0.0', '0.0'],
['0.0', '0.0']])
>>> B = A.copy()
>>> B[0,0] = 1
>>> B
matrix(
[['1.0', '0.0'],
['0.0', '0.0']])
>>> A
matrix(
[['0.0', '0.0'],
['0.0', '0.0']])
Finally, it is possible to convert a matrix to a nested list. This is very useful,
as most Python libraries involving matrices or arrays (namely NumPy or SymPy)
support this format::
>>> B.tolist()
[[mpf('1.0'), mpf('0.0')], [mpf('0.0'), mpf('0.0')]]
Matrix operations
-----------------
You can add and subtract matrices of compatible dimensions::
>>> A = matrix([[1, 2], [3, 4]])
>>> B = matrix([[-2, 4], [5, 9]])
>>> A + B
matrix(
[['-1.0', '6.0'],
['8.0', '13.0']])
>>> A - B
matrix(
[['3.0', '-2.0'],
['-2.0', '-5.0']])
>>> A + ones(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...", line 238, in __add__
raise ValueError('incompatible dimensions for addition')
ValueError: incompatible dimensions for addition
It is possible to multiply or add matrices and scalars. In the latter case the
operation will be done element-wise::
>>> A * 2
matrix(
[['2.0', '4.0'],
['6.0', '8.0']])
>>> A / 4
matrix(
[['0.25', '0.5'],
['0.75', '1.0']])
>>> A - 1
matrix(
[['0.0', '1.0'],
['2.0', '3.0']])
Of course you can perform matrix multiplication, if the dimensions are
compatible::
>>> A * B
matrix(
[['8.0', '22.0'],
['14.0', '48.0']])
>>> matrix([[1, 2, 3]]) * matrix([[-6], [7], [-2]])
matrix(
[['2.0']])
You can raise powers of square matrices::
>>> A**2
matrix(
[['7.0', '10.0'],
['15.0', '22.0']])
Negative powers will calculate the inverse::
>>> A**-1
matrix(
[['-2.0', '1.0'],
['1.5', '-0.5']])
>>> nprint(A * A**-1, 3)
[ 1.0 1.08e-19]
[-2.17e-19 1.0]
Matrix transposition is straightforward::
>>> A = ones(2, 3)
>>> A
matrix(
[['1.0', '1.0', '1.0'],
['1.0', '1.0', '1.0']])
>>> A.T
matrix(
[['1.0', '1.0'],
['1.0', '1.0'],
['1.0', '1.0']])
Norms
.....
Sometimes you need to know how "large" a matrix or vector is. Due to their
multidimensional nature it's not possible to compare them, but there are
several functions to map a matrix or a vector to a positive real number, the
so called norms.
.. autofunction :: mpmath.norm
.. autofunction :: mpmath.mnorm
Linear algebra
--------------
Determinant and Rank
....................
.. autofunction :: mpmath.det
.. autofunction :: mpmath.rank
Decompositions
..............
.. autofunction :: mpmath.cholesky
Linear equations
................
Basic linear algebra is implemented; you can for example solve the linear
equation system::
x + 2*y = -10
3*x + 4*y = 10
using ``lu_solve``::
>>> A = matrix([[1, 2], [3, 4]])
>>> b = matrix([-10, 10])
>>> x = lu_solve(A, b)
>>> x
matrix(
[['30.0'],
['-20.0']])
If you don't trust the result, use ``residual`` to calculate
the residual `||A x-b||`::
>>> residual(A, x, b)
matrix(
[['3.46944695195361e-18'],
['3.46944695195361e-18']])
>>> str(eps)
'2.22044604925031e-16'
As you can see, the solution is quite accurate. The error is caused by the
inaccuracy of the internal floating-point arithmetic. Though, it's even smaller
than the current machine epsilon, which basically means you can trust the
result.
If you need more speed, use NumPy, or use ``fp`` instead ``mp`` matrices
and methods::
>>> A = fp.matrix([[1, 2], [3, 4]])
>>> b = fp.matrix([-10, 10])
>>> fp.lu_solve(A, b)
matrix(
[['29.999999999999996'],
['-19.999999999999996']])
``lu_solve`` accepts overdetermined systems. It is usually not possible to solve
such systems, so the residual is minimized instead. Internally this is done
using Cholesky decomposition to compute a least squares approximation. This means
that that ``lu_solve`` will square the errors. If you can't afford this, use
``qr_solve`` instead. It is twice as slow but more accurate, and it calculates
the residual automatically.
.. autofunction:: mpmath.lu_solve
Matrix factorization
....................
The function ``lu`` computes an explicit LU factorization of a matrix::
>>> P, L, U = lu(matrix([[0,2,3],[4,5,6],[7,8,9]]))
>>> print(P)
[0.0 0.0 1.0]
[1.0 0.0 0.0]
[0.0 1.0 0.0]
>>> print(L)
[ 1.0 0.0 0.0]
[ 0.0 1.0 0.0]
[0.571428571428571 0.214285714285714 1.0]
>>> print(U)
[7.0 8.0 9.0]
[0.0 2.0 3.0]
[0.0 0.0 0.214285714285714]
>>> print(P.T*L*U)
[0.0 2.0 3.0]
[4.0 5.0 6.0]
[7.0 8.0 9.0]
The function ``qr`` computes a QR factorization of a matrix::
>>> A = matrix([[1, 2], [3, 4], [1, 1]])
>>> Q, R = qr(A)
>>> print(Q)
[-0.301511344577764 0.861640436855329 0.408248290463863]
[-0.904534033733291 -0.123091490979333 -0.408248290463863]
[-0.301511344577764 -0.492365963917331 0.816496580927726]
>>> print(R)
[-3.3166247903554 -4.52267016866645]
[ 0.0 0.738548945875996]
[ 0.0 0.0]
>>> print(Q * R)
[1.0 2.0]
[3.0 4.0]
[1.0 1.0]
>>> print(chop(Q.T * Q))
[1.0 0.0 0.0]
[0.0 1.0 0.0]
[0.0 0.0 1.0]
The singular value decomposition
................................
The routines ``svd_r`` and ``svd_c`` compute the singular value decomposition
of a real or complex matrix A. ``svd`` is an unified interface calling
either ``svd_r`` or ``svd_c`` depending on whether *A* is real or complex.
Given *A*, two orthogonal (*A* real) or unitary (*A* complex) matrices *U* and *V*
are calculated such that
.. math ::
A = U S V, \quad U' U = 1, \quad V V' = 1
where *S* is a suitable shaped matrix whose off-diagonal elements are zero.
Here ' denotes the hermitian transpose (i.e. transposition and complex
conjugation). The diagonal elements of *S* are the singular values of *A*,
i.e. the square roots of the eigenvalues of `A' A` or `A A'`.
Examples::
>>> from mpmath import mp
>>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]])
>>> S = mp.svd_r(A, compute_uv = False)
>>> print(S)
[6.0]
[3.0]
[1.0]
>>> U, S, V = mp.svd_r(A)
>>> print(mp.chop(A - U * mp.diag(S) * V))
[0.0 0.0 0.0]
[0.0 0.0 0.0]
[0.0 0.0 0.0]
The Schur decomposition
.......................
This routine computes the Schur decomposition of a square matrix *A*.
Given *A*, a unitary matrix *Q* is determined such that
.. math ::
Q' A Q = R, \quad Q' Q = Q Q' = 1
where *R* is an upper right triangular matrix. Here ' denotes the
hermitian transpose (i.e. transposition and conjugation).
Examples::
>>> from mpmath import mp
>>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])
>>> Q, R = mp.schur(A)
>>> mp.nprint(R, 3)
[2.0 0.417 2.53]
[0.0 4.0 4.74]
[0.0 0.0 9.0]
>>> print(mp.chop(A - Q * R * Q.transpose_conj()))
[0.0 0.0 0.0]
[0.0 0.0 0.0]
[0.0 0.0 0.0]
The eigenvalue problem
......................
The routine ``eig`` solves the (ordinary) eigenvalue problem for a real or complex
square matrix *A*. Given *A*, a vector *E* and matrices *ER* and *EL* are calculated such that
.. code ::
A ER[:,i] = E[i] ER[:,i]
EL[i,:] A = EL[i,:] E[i]
*E* contains the eigenvalues of *A*. The columns of *ER* contain the right eigenvectors
of *A* whereas the rows of *EL* contain the left eigenvectors.
Examples::
>>> from mpmath import mp
>>> A = mp.matrix([[3, -1, 2], [2, 5, -5], [-2, -3, 7]])
>>> E, ER = mp.eig(A)
>>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))
[0.0]
[0.0]
[0.0]
>>> E, EL, ER = mp.eig(A,left = True, right = True)
>>> E, EL, ER = mp.eig_sort(E, EL, ER)
>>> mp.nprint(E)
[2.0, 4.0, 9.0]
>>> print(mp.chop(A * ER[:,0] - E[0] * ER[:,0]))
[0.0]
[0.0]
[0.0]
>>> print(mp.chop( EL[0,:] * A - EL[0,:] * E[0]))
[0.0 0.0 0.0]
See also [Stoer]_ and [Kresser]_.
The symmetric eigenvalue problem
................................
The routines ``eigsy`` and ``eighe`` solve the (ordinary) eigenvalue problem
for a real symmetric or complex hermitian square matrix *A*.
``eigh`` is an unified interface for this two functions calling either
``eigsy`` or ``eighe`` depending on whether *A* is real or complex.
Given *A*, an orthogonal (*A* real) or unitary matrix *Q* (*A* complex) is
calculated which diagonalizes A:
.. math ::
Q' A Q = \operatorname{diag}(E), \quad Q Q' = Q' Q = 1
Here diag(*E*) a is diagonal matrix whose diagonal is *E*.
' denotes the hermitian transpose (i.e. ordinary transposition and
complex conjugation).
The columns of *Q* are the eigenvectors of *A* and *E* contains the eigenvalues:
.. code ::
A Q[:,i] = E[i] Q[:,i]
Examples::
>>> from mpmath import mp
>>> A = mp.matrix([[3, 2], [2, 0]])
>>> E = mp.eigsy(A, eigvals_only = True)
>>> print(E)
[-1.0]
[ 4.0]
>>> A = mp.matrix([[1, 2], [2, 3]])
>>> E, Q = mp.eigsy(A) # alternative: E, Q = mp.eigh(A)
>>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))
[0.0]
[0.0]
>>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]])
>>> E, Q = mp.eighe(A) # alternative: E, Q = mp.eigh(A)
>>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))
[0.0]
[0.0]
See also [Golub]_, [GolubWelsch]_, [Stoer]_ and [Stroud]_.
Determinant
...........
The determinant of a square matrix is computed by the
function ``det``::
>>> from mpmath import mp
>>> A = mp.matrix([[7, 2], [1.5, 3]])
>>> print(mp.det(A))
18.0
Interval and double-precision matrices
--------------------------------------
The ``iv.matrix`` and ``fp.matrix`` classes convert inputs
to intervals and Python floating-point numbers respectively.
Interval matrices can be used to perform linear algebra operations
with rigorous error tracking::
>>> a = iv.matrix([['0.1','0.3','1.0'],
... ['7.1','5.5','4.8'],
... ['3.2','4.4','5.6']])
>>>
>>> b = iv.matrix(['4','0.6','0.5'])
>>> c = iv.lu_solve(a, b)
>>> print(c)
[ [5.2582327113062393041, 5.2582327113062749951]]
[[-13.155049396267856583, -13.155049396267821167]]
[ [7.4206915477497212555, 7.4206915477497310922]]
>>> print(a*c)
[ [3.9999999999999866773, 4.0000000000000133227]]
[[0.59999999999972430942, 0.60000000000027142733]]
[[0.49999999999982236432, 0.50000000000018474111]]
Matrix functions
----------------
.. autofunction :: mpmath.expm
.. autofunction :: mpmath.cosm
.. autofunction :: mpmath.sinm
.. autofunction :: mpmath.sqrtm
.. autofunction :: mpmath.logm
.. autofunction :: mpmath.powm
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+5
View File
@@ -0,0 +1,5 @@
# Airy function Ai(x), Ai'(x) and int_0^x Ai(t) dt on the real line
f = airyai
f_diff = lambda z: airyai(z, derivative=1)
f_int = lambda z: airyai(z, derivative=-1)
plot([f, f_diff, f_int], [-10,5])
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

+2
View File
@@ -0,0 +1,2 @@
# Airy function Ai(z) in the complex plane
cplot(airyai, [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+6
View File
@@ -0,0 +1,6 @@
# Kelvin functions ber_n(x) and bei_n(x) on the real line for n=0,2
f0 = lambda x: ber(0,x)
f1 = lambda x: bei(0,x)
f2 = lambda x: ber(2,x)
f3 = lambda x: bei(2,x)
plot([f0,f1,f2,f3],[0,10],[-10,10])
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+6
View File
@@ -0,0 +1,6 @@
# Modified Bessel function I_n(x) on the real line for n=0,1,2,3
i0 = lambda x: besseli(0,x)
i1 = lambda x: besseli(1,x)
i2 = lambda x: besseli(2,x)
i3 = lambda x: besseli(3,x)
plot([i0,i1,i2,i3],[0,5],[0,5])
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+2
View File
@@ -0,0 +1,2 @@
# Modified Bessel function I_n(z) in the complex plane
cplot(lambda z: besseli(1,z), [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+6
View File
@@ -0,0 +1,6 @@
# Bessel function J_n(x) on the real line for n=0,1,2,3
j0 = lambda x: besselj(0,x)
j1 = lambda x: besselj(1,x)
j2 = lambda x: besselj(2,x)
j3 = lambda x: besselj(3,x)
plot([j0,j1,j2,j3],[0,14])
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+2
View File
@@ -0,0 +1,2 @@
# Bessel function J_n(z) in the complex plane
cplot(lambda z: besselj(1,z), [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+6
View File
@@ -0,0 +1,6 @@
# Modified Bessel function of 2nd kind K_n(x) on the real line for n=0,1,2,3
k0 = lambda x: besselk(0,x)
k1 = lambda x: besselk(1,x)
k2 = lambda x: besselk(2,x)
k3 = lambda x: besselk(3,x)
plot([k0,k1,k2,k3],[0,8],[0,5])
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+2
View File
@@ -0,0 +1,2 @@
# Modified Bessel function of 2nd kind K_n(z) in the complex plane
cplot(lambda z: besselk(1,z), [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+6
View File
@@ -0,0 +1,6 @@
# Bessel function of 2nd kind Y_n(x) on the real line for n=0,1,2,3
y0 = lambda x: bessely(0,x)
y1 = lambda x: bessely(1,x)
y2 = lambda x: bessely(2,x)
y3 = lambda x: bessely(3,x)
plot([y0,y1,y2,y3],[0,10],[-4,1])
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+2
View File
@@ -0,0 +1,2 @@
# Bessel function of 2nd kind Y_n(z) in the complex plane
cplot(lambda z: bessely(1,z), [-8,8], [-8,8], points=50000)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+5
View File
@@ -0,0 +1,5 @@
# Airy function Bi(x), Bi'(x) and int_0^x Bi(t) dt on the real line
f = airybi
f_diff = lambda z: airybi(z, derivative=1)
f_int = lambda z: airybi(z, derivative=-1)
plot([f, f_diff, f_int], [-10,2], [-1,2])
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

+2
View File
@@ -0,0 +1,2 @@
# Airy function Bi(z) in the complex plane
cplot(airybi, [-8,8], [-8,8], points=50000)
+22
View File
@@ -0,0 +1,22 @@
import os.path
import glob
for f in glob.glob("*.py"):
if "buildplots" in f or os.path.exists(f[:-3]+".png"):
continue
print("Processing", f)
code = open(f).readlines()
code = ["from mpmath import *; mp.dps=5"] + code
for i in range(len(code)):
l = code[i].rstrip()
if "cplot(" in l:
l = l[:-1] + (", dpi=45, file='%s.png', verbose=True)" % f[:-3])
code[i] = l
elif "splot(" in l:
l = l[:-1] + (", dpi=45, file='%s.png')" % f[:-3])
code[i] = l
elif "plot(" in l:
l = l[:-1] + (", dpi=45, file='%s.png')" % f[:-3])
code[i] = l
code = "\n".join(code)
exec(code)
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+7
View File
@@ -0,0 +1,7 @@
# Chebyshev polynomials T_n(x) on [-1,1] for n=0,1,2,3,4
f0 = lambda x: chebyt(0,x)
f1 = lambda x: chebyt(1,x)
f2 = lambda x: chebyt(2,x)
f3 = lambda x: chebyt(3,x)
f4 = lambda x: chebyt(4,x)
plot([f0,f1,f2,f3,f4],[-1,1])
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+7
View File
@@ -0,0 +1,7 @@
# Chebyshev polynomials U_n(x) on [-1,1] for n=0,1,2,3,4
f0 = lambda x: chebyu(0,x)
f1 = lambda x: chebyu(1,x)
f2 = lambda x: chebyu(2,x)
f3 = lambda x: chebyu(3,x)
f4 = lambda x: chebyu(4,x)
plot([f0,f1,f2,f3,f4],[-1,1])
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+7
View File
@@ -0,0 +1,7 @@
# Regular Coulomb wave functions -- equivalent to figure 14.3 in A&S
F1 = lambda x: coulombf(0,0,x)
F2 = lambda x: coulombf(0,1,x)
F3 = lambda x: coulombf(0,5,x)
F4 = lambda x: coulombf(0,10,x)
F5 = lambda x: coulombf(0,x/2,x)
plot([F1,F2,F3,F4,F5], [0,25], [-1.2,1.6])
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

+2
View File
@@ -0,0 +1,2 @@
# Regular Coulomb wave function in the complex plane
cplot(lambda z: coulombf(1,1,z), points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+7
View File
@@ -0,0 +1,7 @@
# Irregular Coulomb wave functions -- equivalent to figure 14.5 in A&S
F1 = lambda x: coulombg(0,0,x)
F2 = lambda x: coulombg(0,1,x)
F3 = lambda x: coulombg(0,5,x)
F4 = lambda x: coulombg(0,10,x)
F5 = lambda x: coulombg(0,x/2,x)
plot([F1,F2,F3,F4,F5], [0,30], [-2,2])
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

+2
View File
@@ -0,0 +1,2 @@
# Irregular Coulomb wave function in the complex plane
cplot(lambda z: coulombg(1,1,z), points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+7
View File
@@ -0,0 +1,7 @@
# Elliptic integral E(z,m) for some different m
f1 = lambda z: ellipe(z,-2)
f2 = lambda z: ellipe(z,-1)
f3 = lambda z: ellipe(z,0)
f4 = lambda z: ellipe(z,1)
f5 = lambda z: ellipe(z,2)
plot([f1,f2,f3,f4,f5], [0,pi], [0,4])
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+7
View File
@@ -0,0 +1,7 @@
# Elliptic integral F(z,m) for some different m
f1 = lambda z: ellipf(z,-1)
f2 = lambda z: ellipf(z,-0.5)
f3 = lambda z: ellipf(z,0)
f4 = lambda z: ellipf(z,0.5)
f5 = lambda z: ellipf(z,1)
plot([f1,f2,f3,f4,f5], [0,pi], [0,4])
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+2
View File
@@ -0,0 +1,2 @@
# Complete elliptic integrals K(m) and E(m)
plot([ellipk, ellipe], [-2,1], [0,3], points=600)
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+7
View File
@@ -0,0 +1,7 @@
# Elliptic integral Pi(n,z,m) for some different n, m
f1 = lambda z: ellippi(0.9,z,0.9)
f2 = lambda z: ellippi(0.5,z,0.5)
f3 = lambda z: ellippi(-2,z,-0.9)
f4 = lambda z: ellippi(-0.5,z,0.5)
f5 = lambda z: ellippi(-1,z,0.5)
plot([f1,f2,f3,f4,f5], [0,pi], [0,4])
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+2
View File
@@ -0,0 +1,2 @@
# Scorer function Gi(x) and Gi'(x) on the real line
plot([scorergi, diffun(scorergi)], [-10,10])
Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

+2
View File
@@ -0,0 +1,2 @@
# Scorer function Gi(z) in the complex plane
cplot(scorergi, [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+6
View File
@@ -0,0 +1,6 @@
# Hankel function H1_n(x) on the real line for n=0,1,2,3
h0 = lambda x: hankel1(0,x)
h1 = lambda x: hankel1(1,x)
h2 = lambda x: hankel1(2,x)
h3 = lambda x: hankel1(3,x)
plot([h0,h1,h2,h3],[0,6],[-2,1])
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

+2
View File
@@ -0,0 +1,2 @@
# Hankel function H1_n(z) in the complex plane
cplot(lambda z: hankel1(1,z), [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+6
View File
@@ -0,0 +1,6 @@
# Hankel function H2_n(x) on the real line for n=0,1,2,3
h0 = lambda x: hankel2(0,x)
h1 = lambda x: hankel2(1,x)
h2 = lambda x: hankel2(2,x)
h3 = lambda x: hankel2(3,x)
plot([h0,h1,h2,h3],[0,6],[-1,2])
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

+2
View File
@@ -0,0 +1,2 @@
# Hankel function H2_n(z) in the complex plane
cplot(lambda z: hankel2(1,z), [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+7
View File
@@ -0,0 +1,7 @@
# Hermite polynomials H_n(x) on the real line for n=0,1,2,3,4
f0 = lambda x: hermite(0,x)
f1 = lambda x: hermite(1,x)
f2 = lambda x: hermite(2,x)
f3 = lambda x: hermite(3,x)
f4 = lambda x: hermite(4,x)
plot([f0,f1,f2,f3,f4],[-2,2],[-25,25])
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+2
View File
@@ -0,0 +1,2 @@
# Scorer function Hi(x) and Hi'(x) on the real line
plot([scorerhi, diffun(scorerhi)], [-10,2], [0,2])
Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+2
View File
@@ -0,0 +1,2 @@
# Scorer function Hi(z) in the complex plane
cplot(scorerhi, [-8,8], [-8,8], points=50000)
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+6
View File
@@ -0,0 +1,6 @@
# Kelvin functions ker_n(x) and kei_n(x) on the real line for n=0,2
f0 = lambda x: ker(0,x)
f1 = lambda x: kei(0,x)
f2 = lambda x: ker(2,x)
f3 = lambda x: kei(2,x)
plot([f0,f1,f2,f3],[0,5],[-1,4])

Some files were not shown because too many files have changed in this diff Show More