任意精度演算ライブラリ mpmath#

mpmath はPython 用の任意精度浮動小数点演算のライブラリ。 以下のように pip コマンドで簡単にインストールできる。

pip install mpmath

使用例#

オブジェクト生成#

mpmath.mpf で浮動小数点数のオブジェクトを作る。

import mpmath

# 整数から作ってみる。
mpmath.mpf(2)
mpf('2.0')
# 文字列から作ってみる。
mpmath.mpf("0.5")
mpf('0.5')

演算子による演算#

基本的な演算子についてはそのまま使用できる。

# 2 の 0.5 乗で平方根を求めてみる。
mpmath.mpf(2) ** mpmath.mpf(0.5)
mpf('1.4142135623730951')

精度の指定#

mpmath.mp.dps, mpmath.mp.prec などで精度を指定する。

# 10 進数としての精度を設定
mpmath.mp.dps = 50

# 計算の精度が変化する。
mpmath.mpf(2) ** mpmath.mpf(0.5)
mpf('1.4142135623730950488016887242096980785696718753769468')
# 2 進数としての精度を設定
mpmath.mp.prec = 100

# 計算の精度が変化する。
mpmath.mpf(2) ** mpmath.mpf(0.5)
mpf('1.4142135623730950488016887242092')

各種定数#

数学の定数が色々と用意されている。

# ここでの結果は 50 桁表示しておく。
mpmath.mp.dps = 50
# 円周率
mpmath.pi()
mpf('3.1415926535897932384626433832795028841971693993751068')
# 自然対数の底
mpmath.e()
mpf('2.7182818284590452353602874713526624977572470936999577')
# 黄金比
mpmath.phi()
mpf('1.6180339887498948482045868343656381177203091798057638')

他は公式ドキュメントを参照。

数学の関数#

exp, sin など様々な数学の関数が用意されている。

mpmath.exp(mpmath.mpf(1))
mpf('2.7182818284590452353602874713526624977572470936999577')
mpmath.sin(mpmath.mpf("0.25") * mpmath.pi)
mpf('0.70710678118654752440084436210484903928483593768847475')
mpmath.sqrt(mpmath.mpf(3))
mpf('1.732050807568877293527446341505872366942805253810381')

公式ドキュメントを見ると、他にも様々な関数が実装されている。

Note

楕円関数 su のような珍しい関数もあり、サポートが幅広い。

数値積分#

数値積分の機能もある。

例えば、

\[ 4 \int_0^1 \frac{1}{1 + x^2} dx = \pi \]

を以下のように計算できる。

4 * mpmath.quad(lambda x: 1 / (1 + x ** 2), [0, 1])
mpf('3.1415926535897932384626433832795028841971693993751068')

無限の区間でも計算できる。

mpmath.quad(lambda x: 1 / (1 + x ** 2), [-mpmath.inf, mpmath.inf])
mpf('3.1415926535897932384626433832795028841971693993751068')

課題#

  • 2023/12/10 時点で、まだ 2 進数、16 進数での入出力に対応していない。