added rational numbers

This commit is contained in:
2023-05-24 22:47:16 +08:00
parent d4f64d25a0
commit 1e580cd6da
6 changed files with 278 additions and 51 deletions

View File

@@ -2,9 +2,10 @@ from random import initRand, rand
from nwo/utils import `...`
from mmath/smatrix import det, lu, lup, lu_det, lup, det, from_pivot, invert, identity,
newSMatrix, SMatrix, clone, tril, triu, lu_solve, `$`, `*`, `-`, `+`, `-=`, `+=`, `==`, `*`, norm2, newSMatrixFromArray,
gauss_jordan_high, gauss_jordan_low, transpose
gauss_jordan_high, gauss_jordan_low, transpose, squared_norm2
from mmath/svector import buildSVector, `-`, abs, norm, Svector
from mmath/pivot import SingularMatrixError
from mmath/rational import newRational, Rational, one, zero, abs, `>`, `<`, `==`, `*`, `+`, `-`, `/`, `/=`, `+=`, `sqrt`
import unittest
suite "Nim linear algebra library":
@@ -58,19 +59,19 @@ suite "Nim linear algebra library":
test "Inverse":
let err = test_matrix * test_matrix.invert() - identity[3, float32]()
check(err.norm2() < 1e-5)
test "LU decomposition":
var rng = initRand(101325)
var arr : array[0..(25 - 1), float32]
var arr : array[0..(25 - 1), Rational[int64]]
for i in 0..<arr.len:
arr[i] = rng.rand(-4f32..4f32)
let mtx = newSMatrixFromArray[5, 5, float32](arr)
var lu = mtx.clone()
arr[i] = newRational(rng.rand(-20..20).int64, 20.int64)
let mtx = newSMatrixFromArray[5, 5, Rational[int64]](arr)
var lu = mtx.clone()
let pivot = lu.lup()
let l = lu.tril(1.0)
let l = lu.tril(Rational[int64].one)
let u = lu.triu()
let err = pivot * mtx - (l * u)
check(err.norm2() < 1e-5)
check(err.squared_norm2() == Rational[int64].zero)
test "Linear system solve":
var rng = initRand(101325)