sangi
C++23 総合数学ライブラリ
C++23 / LGPL v3 / 外部依存ゼロsangi は、多倍長演算 (Int, Float, Rational) を核に、 複素数・多項式・行列・特殊関数・FFT・Lie 群などを ひとつの統一的なフレームワークで提供する C++23 数学ライブラリである。
ライブラリ名の sangi は日本の和算で用いられた計算棒 算木 (さんぎ) に由来し、算木の七にあたる は、奇しくも円周率 π の形と重なる。
| 数 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| 算木 |
1〜5 は縦棒を並べ、6〜9 に横棒を加えるところは、後世のそろばんに似ている。0 は空欄によって表された。
多倍長演算
Int (整数)・Float (浮動小数点)・Rational (有理数) の 3 型。 BMI2/ADX 命令による高速 mpn 演算、7 段乗算アルゴリズム (Basecase → Karatsuba → Toom-3 → Toom-4 → Toom-6 → Toom-8 → NTT) を搭載。
NaN / Infinity 安全
Int・Float・Rational のすべてで NaN と Infinity が安全に伝播する。 ゼロ除算でクラッシュしない。
C++23 Concepts
Ring・Field・VectorSpace など 50 以上の代数的 concepts を定義。 型安全なジェネリックアルゴリズムを記述できる。
80+ 特殊関数
Bessel・Airy・Gamma・Zeta・楕円積分・超幾何関数など。
double・Complex<double>・Float (多倍長) で利用可能。
数値アルゴリズム
線形代数 (LU/QR/SVD)・求根・補間・FFT。
Matrix<Float> のように多倍長型との組み合わせも可能。
Lie 群 / 代数
SO(2)・SE(2)・SO(3)・SE(3) の exp/log・ヤコビアン・随伴表現。 左摂動モデル (GTSAM 規約)。
API リファレンス
コア型 (数値型)
代数構造 (ヘッダーオンリー)
アルゴリズムモジュール (ヘッダーオンリー)
アルゴリズム解説
各クラスの内部で使用されるアルゴリズムの詳細。閾値、計算量、設計判断の根拠を扱う。
線形代数
求根
最適化
補間
近似
特殊関数
多項式
スペクトル変換
多倍長算術
整数
有理数
複素数
浮動小数点
デモ
sangi の機能を使った実行例。ソースコード付きで、手元でビルド・実行できる。
コード例
Int — 多倍長整数
#include <math/core/mp/Int.hpp>
#include <iostream>
using namespace sangi;
int main() {
Int a("123456789012345678901234567890");
Int b("987654321098765432109876543210");
std::cout << "a + b = " << a + b << std::endl;
std::cout << "a * b = " << a * b << std::endl;
std::cout << "gcd = " << gcd(a, b) << std::endl;
// 素数判定 (Miller-Rabin)
Int p("170141183460469231731687303715884105727"); // 2^127 - 1
std::cout << p << " is prime: " << std::boolalpha
<< isProbablePrime(p) << std::endl;
// NaN/Infinity 安全伝播
Int zero;
Int nan = Int(1) / zero;
std::cout << "1/0 = " << nan << std::endl; // NaN
}
Float — 多倍長浮動小数点
#include <math/core/mp/Float.hpp>
#include <iostream>
using namespace sangi;
int main() {
int prec = 50; // 50 桁精度
Float::setDefaultPrecision(prec);
// 数学定数 (スレッドローカルキャッシュ、2 回目以降は即座に返る)
Float pi = Float::pi(prec); // π を 50 桁で計算 (Chudnovsky)
// 超越関数
Float y = exp(pi, prec); // e^π
Float z = log(y, prec); // log(e^π) = π
std::cout << "exp(pi) = " << y.toDecimalString(prec) << std::endl;
std::cout << "log(exp(pi)) = " << z.toDecimalString(prec) << std::endl;
// 三角関数
Float s = sin(pi / Float(6, prec), prec); // sin(π/6) = 0.5
std::cout << "sin(pi/6) = " << s.toDecimalString(20) << std::endl;
}
Rational — 有理数
#include <math/core/mp/Rational.hpp>
#include <iostream>
using namespace sangi;
int main() {
Rational a(1, 3); // 1/3
Rational b(1, 6); // 1/6
Rational sum = a + b;
std::cout << "1/3 + 1/6 = " << sum << std::endl; // 1/2 (自動約分)
Rational product = a * b;
std::cout << "1/3 * 1/6 = " << product << std::endl; // 1/18
// 多倍長整数との組み合わせ
Rational big(Int("1000000000000000000"), Int("3"));
std::cout << big << std::endl;
}
Complex — 複素数
#include <math/core/Complex.hpp>
#include <iostream>
using namespace sangi;
using namespace sangi::literals;
int main() {
Complex<double> z(3.0, 4.0);
std::cout << "z = " << z << std::endl; // (3, 4)
std::cout << "|z| = " << abs(z) << std::endl; // 5
std::cout << "arg = " << arg(z) << std::endl; // 0.9273
std::cout << "conj = " << conj(z) << std::endl; // (3, -4)
// Euler's formula: e^(i*pi) = -1
auto euler = exp(Complex<double>(0, std::numbers::pi));
std::cout << "e^(i*pi) = " << euler << std::endl; // (-1, 0)
// User-defined literal
auto w = 2.0 + 3.0_i;
std::cout << "w*w = " << w * w << std::endl; // (-5, 12)
}
Vector — 数値ベクトル
#include <math/core/vector.hpp>
#include <iostream>
using namespace sangi;
int main() {
Vector<double> a{1.0, 2.0, 3.0};
Vector<double> b{4.0, 5.0, 6.0};
// 式テンプレート: 中間オブジェクトなしで評価
Vector<double> c = 2.0 * a + b;
std::cout << "dot(a, b) = " << dot(a, b) << std::endl; // 32
std::cout << "norm(a) = " << norm(a) << std::endl; // 3.74166
// 3D 外積 (StaticVector)
StaticVector<double, 3> i{1, 0, 0}, j{0, 1, 0};
auto k = cross(i, j); // [0, 0, 1]
}
Matrix — 行列
#include <math/core/matrix.hpp>
#include <math/core/mp/Rational.hpp>
#include <math/linalg/decomposition.hpp>
#include <iostream>
using namespace sangi;
using namespace sangi::algorithms;
int main() {
// 行列演算
Matrix<double> A({{2, 1, -1}, {-3, -1, 2}, {-2, 1, 2}});
Vector<double> b({8, -11, -3});
auto x = lu_solve(A, b); // x = {2, 3, -1}
// operator^: 転置, 逆行列, 冪乗
auto At = A ^ 'T'; // 転置
auto Ainv = A ^ (-1); // 逆行列
auto A3 = A ^ 3; // A*A*A
// Rational で厳密な逆行列
Matrix<Rational> H(3, 3);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
H(i, j) = Rational(1, i + j + 1); // Hilbert 行列
auto Hinv = lu_inverse(H); // 全要素が整数 (厳密)
auto I = H * Hinv; // 厳密に単位行列
}
LinAlg — 線形代数
#include <math/core/matrix.hpp>
#include <math/linalg/decomposition.hpp>
#include <math/linalg/eigenvalues.hpp>
#include <iostream>
using namespace sangi;
using namespace sangi::algorithms;
int main() {
Matrix<double> A({{4, 1, 1}, {1, 3, 0}, {1, 0, 2}});
// SVD 分解
auto [U, sigma, Vt] = svd_decomposition(A);
// 対称固有値
auto [evals, evecs] = eigen_symmetric(A);
// ガウス消去法 (ピボット戦略選択)
Vector<double> b({6, 4, 3});
auto x = gaussian_elimination(A, b, PivotStrategy::Full);
// Bareiss: 整数行列の行列式 (除算なし)
Matrix<int> M({{1, 2, 3}, {4, 5, 6}, {7, 8, 10}});
auto det = bareiss_determinant(M); // -3
}
Polynomial — 多項式
#include <math/core/polynomial.hpp>
#include <iostream>
using namespace sangi;
int main() {
// x^2 - 1 = (x-1)(x+1)
Polynomial<double> p({-1, 0, 1}); // -1 + 0x + x^2
Polynomial<double> q({1, 1}); // 1 + x
auto [quot, rem] = p.divmod(q);
std::cout << "quot = " << quot << std::endl; // -1 + x
std::cout << "rem = " << rem << std::endl; // 0
// 微分・積分
auto dp = p.derivative(); // 2x
auto ip = p.integral(); // -x + x^3/3
// 求根 (全複素根)
auto roots = findAllRoots(p); // {-1, 1}
}
FFT — 高速フーリエ変換
#include <math/fft/fft.hpp>
#include <math/fft/fft_utils.hpp>
#include <iostream>
using namespace sangi;
int main() {
// 複素 FFT (in-place)
std::vector<Complex<double>> data = {1, 2, 3, 4};
FFT<Complex<double>>::fft(data); // 順変換
FFT<Complex<double>>::ifft(data); // 逆変換 (元に戻る)
// 実数 FFT (N → N/2+1 の複素スペクトル)
std::vector<double> signal = {1, 0, -1, 0, 1, 0, -1, 0};
auto spectrum = RealFFT<double>::fft(signal);
auto amp = amplitude_spectrum<double>(spectrum);
// 多項式乗算 (畳み込み)
std::vector<double> a = {1, 2, 3}, b = {4, 5};
auto c = RealFFT<double>::convolve(a, b); // {4, 13, 22, 15}
}
Roots — 求根アルゴリズム
#include <math/roots/roots.hpp>
#include <math/core/polynomial.hpp>
#include <iostream>
using namespace sangi;
int main() {
// Brent 法: f(x) = x^3 - 2 の根 (= ∛2)
auto f = [](double x) { return x * x * x - 2.0; };
double root = brentRoot(f, 1.0, 2.0);
std::cout << "cbrt(2) = " << root << std::endl; // 1.25992...
// Newton 法: f(x) = sin(x) - 0.5 の根
auto g = [](double x) { return std::sin(x) - 0.5; };
auto dg = [](double x) { return std::cos(x); };
double r2 = newtonRoot(g, dg, 0.5);
std::cout << "arcsin(0.5) = " << r2 << std::endl; // π/6
// 多項式の全複素根 (Aberth-Ehrlich)
Polynomial<double> p({6, -5, 1}); // x^2 - 5x + 6 = (x-2)(x-3)
auto roots = findAllRoots(p);
for (auto& z : roots)
std::cout << z << std::endl; // 2, 3
}
Optimization — 最適化
#include <math/optimization/optimization_nd.hpp>
#include <iostream>
using namespace sangi;
int main() {
using V = Vector<double>;
using M = Matrix<double>;
// Rosenbrock 関数の BFGS 最小化
auto f = [](const V& x) { return (1-x[0])*(1-x[0]) + 100*(x[1]-x[0]*x[0])*(x[1]-x[0]*x[0]); };
auto df = [](const V& x) {
return V{-2*(1-x[0]) - 400*x[0]*(x[1]-x[0]*x[0]),
200*(x[1]-x[0]*x[0])};
};
auto result = bfgs_minimize<double, V, M>(f, df, V{-1, -1});
std::cout << "min at " << result.point << std::endl; // [1, 1]
std::cout << "f(min) = " << result.value << std::endl; // ~0
}
ビルド
必要環境
- 64-bit OS (x86_64 / AArch64)
- CMake 3.20 以降
対応コンパイラ
| コンパイラ | 最低バージョン | ASM 最適化 | 状態 |
|---|---|---|---|
| MSVC (Visual Studio 2022) | 17.6+ | MASM (AVX2 + BMI2 + ADX) | 動作確認済み |
| GCC | 14+ | GAS (AVX2 + BMI2 + ADX) | 動作確認済み |
| Clang | 17+ | GAS (AVX2 + BMI2 + ADX) | 動作確認済み |
対応環境と性能特性
sangi は 64-bit (x86_64 / AArch64) 環境が必須である。
内部の多倍長演算が 64-bit リムと 128-bit ワイド乗算 (_umul128 / __uint128_t) に依存するため、
32-bit 環境では動作しない。
以下のハードウェア機能が利用可能な場合、自動的に高速パスが有効になる。
| 高速パス | 有効条件 | フォールバック |
|---|---|---|
| AVX2 NTT バタフライ | AVX2 対応 CPU (Intel Haswell 以降 / AMD Zen 以降) | スカラー Montgomery NTT |
| MULX/ADCX/ADOX mpn プリミティブ |
BMI2 + ADX 対応 CPU、x64 (Windows: MASM / Linux: GAS) | C++ ジェネリック実装 (__uint128_t) |
| NTT 並列化 | NTT 長 ≥ 4096 (自動判定) | シングルスレッド |
- Windows x64 + AVX2: すべての高速パスが有効。最高性能。
- Linux x64 + AVX2: GAS アセンブリ (BMI2 + ADX) + AVX2 NTT が有効。Windows 版と同等の性能。
- ARM / Apple Silicon: AVX2・ASM ともに無効。全機能は
__uint128_tベースの C++ 実装で動作するため、x64 ASM 版と比べて多倍長演算は 2〜3 倍程度遅くなると思われる。
ダウンロード
ソースコードをダウンロードして CMake でビルドする。
sangi-source-2026.06.22.zip をダウンロード
ソースコード一覧からファイル単位で閲覧することもできる。
ウイルス対策ソフトによる誤検知について
ソースからビルドした実行ファイルが、ウイルス対策ソフトにより誤検知・隔離される場合がある。
sangi_int.lib には冪剰余 (Montgomery 乗算) と MASM アセンブリカーネルが含まれるため、
ビルドした exe にこれらのコードが静的リンクされる。
隔離は無言で行われ時間差で報告されるため、ビルドに失敗して exe が生成されなかったように見えることがある。 誤検知された場合はビルドディレクトリをウイルス対策ソフトの除外リストに追加すること。
GMP や OpenSSL など他の暗号・多倍長演算ライブラリでも同様の問題が発生する。
ソースからのビルドとサンプル実行
Windows (MSVC)
cd sangi
mkdir build && cd build
cmake .. -G "Visual Studio 17 2022" -A x64
cmake --build . --config Release
ビルド後、サンプルプログラムを実行できる:
examples\Release\example-int.exe
examples\Release\example-float.exe
examples\Release\example-rational.exe
examples\Release\example-vector.exe
examples\Release\example-matrix.exe
examples\Release\example-linalg.exe
examples\Release\example-precision-showdown.exe
examples\Release\example-mp.exe
examples\Release\example-int-demo.exe
examples\Release\example-float-demo.exe
examples\Release\example-rational-demo.exe
examples\Release\example-vector-demo.exe
examples\Release\example-matrix-demo.exe
examples\Release\example-polynomial.exe
examples\Release\example-polynomial-factorization.exe
examples\Release\example-complex.exe
examples\Release\example-roots.exe
examples\Release\example-optimization.exe
examples\Release\example-fft.exe
examples\Release\example-rationalfunction.exe
examples\Release\example-tensor.exe
examples\Release\example-random.exe
examples\Release\example-interpolation.exe
examples\Release\example-approximation.exe
examples\Release\example-specialfunctions.exe
Linux (GCC / Clang)
cd sangi
mkdir build && cd build
cmake .. -DCMAKE_CXX_COMPILER=g++-14 -DCMAKE_BUILD_TYPE=Release # GCC
# cmake .. -DCMAKE_CXX_COMPILER=clang++-17 -DCMAKE_BUILD_TYPE=Release # Clang
cmake --build . -j$(nproc)
ビルド後、サンプルプログラムを実行できる:
./examples/example-int
./examples/example-float
./examples/example-rational
./examples/example-vector
./examples/example-matrix
./examples/example-linalg
./examples/example-precision-showdown
./examples/example-mp
./examples/example-int-demo
./examples/example-float-demo
./examples/example-rational-demo
./examples/example-vector-demo
./examples/example-matrix-demo
./examples/example-polynomial
./examples/example-polynomial-factorization
./examples/example-complex
./examples/example-roots
./examples/example-optimization
./examples/example-fft
./examples/example-rationalfunction
./examples/example-tensor
./examples/example-random
./examples/example-interpolation
./examples/example-approximation
./examples/example-specialfunctions
このほか、ビルドでは example-doc-*-samples(complex・fft・int・linalg など15本)も生成される。これらは API リファレンス(api/*.html)に掲載したコード例が記載どおりの出力になることを確かめるドキュメント検証用プログラムで、学習用サンプルではないため上の実行一覧には含めていない。
自作アプリでの使用
サンプルの動作を確認できたら、自作のプログラムで sangi を使ってみる。
sangi のビルドで生成されたライブラリ (.lib) をリンクする:
// myapp.cpp
#include <math/core/mp/Int.hpp>
#include <iostream>
using namespace sangi;
int main() {
Int a = Int::factorial(100);
std::cout << "100! = " << a << std::endl;
}
Windows (MSVC):
cl /std:c++23 /EHsc /utf-8 /I C:\path\to\sangi\include myapp.cpp ^
C:\path\to\sangi\build\lib\Release\sangi_int.lib ^
C:\path\to\sangi\build\lib\Release\sangi_fft.lib
myapp.exe
Linux (GCC / Clang):
g++-14 -std=c++23 -O2 -I sangi/include myapp.cpp \
sangi/build/lib/libsangi_int.a sangi/build/lib/libsangi_fft.a -lpthread -o myapp
./myapp
CMake を使う場合:
target_include_directories(myapp PRIVATE path/to/sangi/include)
target_link_libraries(myapp PRIVATE
path/to/sangi/build/lib/sangi_int # or libsangi_int.a on Linux
path/to/sangi/build/lib/sangi_fft # Int 乗算に必要
path/to/sangi/build/lib/sangi_float # Float を使う場合
)
リリース履歴
| 2026-06-22 | Interpolation · Approximation · SpecialFunctions 公開 |
| 2026-06-11 | RationalFunction · Random 公開 |
| 2026-05-23 | Tensor 公開 |
| 2026-04-28 | Complex · Optimization 公開 |
| 2026-04-17 | Polynomial · Roots · FFT 公開 |
| 2026-04-10 | Concepts 公開 |
| 2026-04-03 | Matrix · LinAlg 公開 |
| 2026-03-27 | Vector 公開 |
| 2026-03-20 | Rational 公開 |
| 2026-03-13 | Float 公開 |
| 2026-03-02 | Int 公開 |