Browse Source

Cosmetics, more eol whitespace

v2
Christoph Ruegg 14 years ago
parent
commit
c65f6e952c
  1. 2
      src/FSharp/BigRational.fs
  2. 4
      src/FSharp/BigRational.fsi
  3. 6
      src/FSharp/Complex.fsi
  4. 52
      src/FSharp/LinearAlgebra.Double.Matrix.fs
  5. 50
      src/FSharp/LinearAlgebra.Double.Vector.fs
  6. 18
      src/FSharp/LinearAlgebra.fs
  7. 68
      src/FSharp/RandomVariable.fs
  8. 2
      src/FSharpExamples/Apply.fs
  9. 20
      src/FSharpExamples/MCMC.fs
  10. 274
      src/FSharpUnitTests/BigRationalTests.fs
  11. 42
      src/FSharpUnitTests/DenseMatrixTests.fs
  12. 30
      src/FSharpUnitTests/DenseVectorTests.fs
  13. 2
      src/FSharpUnitTests/FsUnit.fs
  14. 128
      src/FSharpUnitTests/MatrixTests.fs
  15. 32
      src/FSharpUnitTests/RandomVariableTests.fs
  16. 10
      src/FSharpUnitTests/SparseMatrixTests.fs
  17. 12
      src/FSharpUnitTests/SparseVectorTests.fs
  18. 56
      src/FSharpUnitTests/Utilities.fs
  19. 118
      src/FSharpUnitTests/VectorTests.fs

2
src/FSharp/BigRational.fs

@ -1,7 +1,5 @@
// First version copied from the F# Power Pack // First version copied from the F# Power Pack
// https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack/math/q.fs // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack/math/q.fs
// (c) Microsoft Corporation. All rights reserved // (c) Microsoft Corporation. All rights reserved
#nowarn "44" // OK to use the "compiler only" function RangeGeneric #nowarn "44" // OK to use the "compiler only" function RangeGeneric

4
src/FSharp/BigRational.fsi

@ -1,7 +1,5 @@
// First version copied from the F# Power Pack // First version copied from the F# Power Pack
// https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack/math/q.fsi // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack/math/q.fsi
// (c) Microsoft Corporation 2005-2009. // (c) Microsoft Corporation 2005-2009.
namespace MathNet.Numerics namespace MathNet.Numerics
@ -93,4 +91,4 @@ namespace MathNet.Numerics
val FromOne : unit -> BigRational val FromOne : unit -> BigRational
val FromInt32 : int32 -> BigRational val FromInt32 : int32 -> BigRational
val FromInt64 : int64 -> BigRational val FromInt64 : int64 -> BigRational
val FromString : string -> BigRational val FromString : string -> BigRational

6
src/FSharp/Complex.fsi

@ -53,7 +53,7 @@ namespace MathNet.Numerics
val mul : complex -> complex -> complex val mul : complex -> complex -> complex
/// Complex division of two complex numbers /// Complex division of two complex numbers
val div : complex -> complex -> complex val div : complex -> complex -> complex
/// Multiply a scalar by a complex number /// Multiply a scalar by a complex number
val smul : float -> complex -> complex val smul : float -> complex -> complex
/// Multiply a complex number by a scalar /// Multiply a complex number by a scalar
@ -156,7 +156,7 @@ namespace MathNet.Numerics
val mul : complex32 -> complex32 -> complex32 val mul : complex32 -> complex32 -> complex32
/// Complex division of two complex numbers /// Complex division of two complex numbers
val div : complex32 -> complex32 -> complex32 val div : complex32 -> complex32 -> complex32
/// Multiply a scalar by a complex number /// Multiply a scalar by a complex number
val smul : float32 -> complex32 -> complex32 val smul : float32 -> complex32 -> complex32
/// Multiply a complex number by a scalar /// Multiply a complex number by a scalar
@ -222,7 +222,7 @@ namespace MathNet.Numerics
/// Constructs a double precision complex number from both the real and imaginary part. /// Constructs a double precision complex number from both the real and imaginary part.
val complex : float -> float -> complex val complex : float -> float -> complex
/// Constructs a single precision complex number from both the real and imaginary part. /// Constructs a single precision complex number from both the real and imaginary part.
val complex32 : float32 -> float32 -> complex32 val complex32 : float32 -> float32 -> complex32

52
src/FSharp/LinearAlgebra.Double.Matrix.fs

@ -35,7 +35,7 @@ open MathNet.Numerics.LinearAlgebra.Generic
/// A module which implements functional matrix operations. /// A module which implements functional matrix operations.
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Matrix = module Matrix =
/// Fold a function over all matrix elements. /// Fold a function over all matrix elements.
let inline fold (f: 'a -> float -> 'a) (acc0: 'a) (A: #Matrix<float>) = let inline fold (f: 'a -> float -> 'a) (acc0: 'a) (A: #Matrix<float>) =
let n = A.RowCount let n = A.RowCount
@ -71,8 +71,8 @@ module Matrix =
let n = A.RowCount let n = A.RowCount
let m = A.ColumnCount let m = A.ColumnCount
Array2D.init n m (fun i j -> (A.Item(i,j))) Array2D.init n m (fun i j -> (A.Item(i,j)))
/// Checks whether a predicate holds for all elements of a matrix. /// Checks whether a predicate holds for all elements of a matrix.
let inline forall (p: float -> bool) (A: #Matrix<float>) = let inline forall (p: float -> bool) (A: #Matrix<float>) =
let mutable b = true let mutable b = true
let mutable i = 0 let mutable i = 0
@ -82,7 +82,7 @@ module Matrix =
j <- j+1 j <- j+1
if j = A.ColumnCount then i <- i+1; j <- 0 if j = A.ColumnCount then i <- i+1; j <- 0
b b
/// Chechks whether a predicate holds for at least one element of a matrix. /// Chechks whether a predicate holds for at least one element of a matrix.
let inline exists (p: float -> bool) (A: #Matrix<float>) = let inline exists (p: float -> bool) (A: #Matrix<float>) =
let mutable b = false let mutable b = false
@ -93,7 +93,7 @@ module Matrix =
j <- j+1 j <- j+1
if j = A.ColumnCount then i <- i+1; j <- 0 if j = A.ColumnCount then i <- i+1; j <- 0
b b
/// Checks whether a position dependent predicate holds for all elements of a matrix. /// Checks whether a position dependent predicate holds for all elements of a matrix.
let inline foralli (p: int -> int -> float -> bool) (A: #Matrix<float>) = let inline foralli (p: int -> int -> float -> bool) (A: #Matrix<float>) =
let mutable b = true let mutable b = true
@ -104,7 +104,7 @@ module Matrix =
j <- j+1 j <- j+1
if j = A.ColumnCount then i <- i+1; j <- 0 if j = A.ColumnCount then i <- i+1; j <- 0
b b
/// Checks whether a position dependent predicate holds for at least one element of a matrix. /// Checks whether a position dependent predicate holds for at least one element of a matrix.
let inline existsi (p: int -> int -> float -> bool) (A: #Matrix<float>) = let inline existsi (p: int -> int -> float -> bool) (A: #Matrix<float>) =
let mutable b = false let mutable b = false
@ -115,7 +115,7 @@ module Matrix =
j <- j+1 j <- j+1
if j = A.ColumnCount then i <- i+1; j <- 0 if j = A.ColumnCount then i <- i+1; j <- 0
b b
/// Map every matrix element using the given function. /// Map every matrix element using the given function.
let inline map (f: float -> float) (A: #Matrix<float>) = let inline map (f: float -> float) (A: #Matrix<float>) =
let N = A.RowCount let N = A.RowCount
@ -125,7 +125,7 @@ module Matrix =
for j=0 to M-1 do for j=0 to M-1 do
C.[i,j] <- f (C.Item(i,j)) C.[i,j] <- f (C.Item(i,j))
C C
/// Map every matrix element using the given position dependent function. /// Map every matrix element using the given position dependent function.
let inline mapi (f: int -> int -> float -> float) (A: #Matrix<float>) = let inline mapi (f: int -> int -> float -> float) (A: #Matrix<float>) =
let N = A.RowCount let N = A.RowCount
@ -135,7 +135,7 @@ module Matrix =
for j=0 to M-1 do for j=0 to M-1 do
C.[i,j] <- f i j (C.Item(i,j)) C.[i,j] <- f i j (C.Item(i,j))
C C
/// In-place map every matrix column using the given position dependent function. /// In-place map every matrix column using the given position dependent function.
let inline inplaceMapCols (f: int -> Vector<float> -> Vector<float>) (A: #Matrix<float>) = let inline inplaceMapCols (f: int -> Vector<float> -> Vector<float>) (A: #Matrix<float>) =
for j = 0 to A.ColumnCount-1 do for j = 0 to A.ColumnCount-1 do
@ -165,19 +165,19 @@ module Matrix =
for i=0 to A.RowCount-1 do for i=0 to A.RowCount-1 do
for j=0 to A.ColumnCount-1 do for j=0 to A.ColumnCount-1 do
A.Item(i,j) <- f i j A.Item(i,j) <- f i j
/// In-place map of every matrix element using a position dependent function. /// In-place map of every matrix element using a position dependent function.
let inline inplaceMapi (f: int -> int -> float -> float) (A: #Matrix<float>) = let inline inplaceMapi (f: int -> int -> float -> float) (A: #Matrix<float>) =
for i=0 to A.RowCount-1 do for i=0 to A.RowCount-1 do
for j=0 to A.ColumnCount-1 do for j=0 to A.ColumnCount-1 do
A.Item(i,j) <- f i j (A.Item(i,j)) A.Item(i,j) <- f i j (A.Item(i,j))
/// Creates a sequence that iterates the non-zero entries in the matrix. /// Creates a sequence that iterates the non-zero entries in the matrix.
let inline nonZeroEntries (A: #Matrix<float>) = let inline nonZeroEntries (A: #Matrix<float>) =
seq { for i in 0 .. A.RowCount-1 do seq { for i in 0 .. A.RowCount-1 do
for j in 0 .. A.ColumnCount-1 do for j in 0 .. A.ColumnCount-1 do
if A.Item(i,j) <> 0.0 then yield (i,j, A.Item(i,j)) } if A.Item(i,j) <> 0.0 then yield (i,j, A.Item(i,j)) }
/// Returns the sum of all elements of a matrix. /// Returns the sum of all elements of a matrix.
let inline sum (A: #Matrix<float>) = let inline sum (A: #Matrix<float>) =
let mutable f = 0.0 let mutable f = 0.0
@ -189,7 +189,7 @@ module Matrix =
/// Returns the sum of the results generated by applying a position dependent function to each column of the matrix. /// Returns the sum of the results generated by applying a position dependent function to each column of the matrix.
let inline sumColsBy (f: int -> Vector<float> -> 'a) (A: #Matrix<float>) = let inline sumColsBy (f: int -> Vector<float> -> 'a) (A: #Matrix<float>) =
A.ColumnEnumerator() |> Seq.map (fun (j,col) -> f j col) |> Seq.reduce (+) A.ColumnEnumerator() |> Seq.map (fun (j,col) -> f j col) |> Seq.reduce (+)
/// Returns the sum of the results generated by applying a position dependent function to each row of the matrix. /// Returns the sum of the results generated by applying a position dependent function to each row of the matrix.
let inline sumRowsBy (f: int -> Vector<float> -> 'a) (A: #Matrix<float>) = let inline sumRowsBy (f: int -> Vector<float> -> 'a) (A: #Matrix<float>) =
A.RowEnumerator() |> Seq.map (fun (i,row) -> f i row) |> Seq.reduce (+) A.RowEnumerator() |> Seq.map (fun (i,row) -> f i row) |> Seq.reduce (+)
@ -200,21 +200,21 @@ module Matrix =
for j=0 to A.ColumnCount-1 do for j=0 to A.ColumnCount-1 do
f (A.Item(i,j)) f (A.Item(i,j))
() ()
/// Iterates over all elements of a matrix using the element indices. /// Iterates over all elements of a matrix using the element indices.
let inline iteri (f: int -> int -> float -> unit) (A: #Matrix<float>) = let inline iteri (f: int -> int -> float -> unit) (A: #Matrix<float>) =
for i=0 to A.RowCount-1 do for i=0 to A.RowCount-1 do
for j=0 to A.ColumnCount-1 do for j=0 to A.ColumnCount-1 do
f i j (A.Item(i,j)) f i j (A.Item(i,j))
() ()
/// Fold one column. /// Fold one column.
let inline foldCol (f: 'a -> float -> 'a) acc (A: #Matrix<float>) k = let inline foldCol (f: 'a -> float -> 'a) acc (A: #Matrix<float>) k =
let mutable macc = acc let mutable macc = acc
for i=0 to A.RowCount-1 do for i=0 to A.RowCount-1 do
macc <- f macc (A.Item(i,k)) macc <- f macc (A.Item(i,k))
macc macc
/// Fold one row. /// Fold one row.
let inline foldRow (f: 'a -> float -> 'a) acc (A: #Matrix<float>) k = let inline foldRow (f: 'a -> float -> 'a) acc (A: #Matrix<float>) k =
let mutable macc = acc let mutable macc = acc
@ -231,7 +231,7 @@ module Matrix =
macc <- f macc (A.Item(i,k)) macc <- f macc (A.Item(i,k))
v.[k] <- macc v.[k] <- macc
v :> Vector<float> v :> Vector<float>
/// Fold all rows into one column vector. /// Fold all rows into one column vector.
let inline foldByRow (f: float -> float -> float) acc (A: #Matrix<float>) = let inline foldByRow (f: float -> float -> float) acc (A: #Matrix<float>) =
let v = new DenseVector(A.RowCount) let v = new DenseVector(A.RowCount)
@ -253,7 +253,7 @@ module DenseMatrix =
for j=0 to m-1 do for j=0 to m-1 do
A.[i,j] <- f i j A.[i,j] <- f i j
A A
/// Create a matrix from a list of float lists. Every list in the master list specifies a row. /// Create a matrix from a list of float lists. Every list in the master list specifies a row.
let inline ofList (fll: float list list) = let inline ofList (fll: float list list) =
let n = List.length fll let n = List.length fll
@ -263,7 +263,7 @@ module DenseMatrix =
if (List.length fl) <> m then failwith "Each subrow must be of the same length." else if (List.length fl) <> m then failwith "Each subrow must be of the same length." else
List.iteri (fun j f -> A.[i,j] <- f) fl) List.iteri (fun j f -> A.[i,j] <- f) fl)
A A
/// Create a matrix from a list of sequences. Every sequence in the master sequence specifies a row. /// Create a matrix from a list of sequences. Every sequence in the master sequence specifies a row.
let inline ofSeq (fss: #seq<#seq<float>>) = let inline ofSeq (fss: #seq<#seq<float>>) =
let n = Seq.length fss let n = Seq.length fss
@ -276,20 +276,20 @@ module DenseMatrix =
/// Create a matrix from a 2D array of floating point numbers. /// Create a matrix from a 2D array of floating point numbers.
let inline ofArray2 (arr: float[,]) = new DenseMatrix(arr) let inline ofArray2 (arr: float[,]) = new DenseMatrix(arr)
/// Create a matrix with the given entries. /// Create a matrix with the given entries.
let inline initDense (n: int) (m: int) (es: #seq<int * int * float>) = let inline initDense (n: int) (m: int) (es: #seq<int * int * float>) =
let A = new DenseMatrix(n,m) let A = new DenseMatrix(n,m)
Seq.iter (fun (i,j,f) -> A.[i,j] <- f) es Seq.iter (fun (i,j,f) -> A.[i,j] <- f) es
A A
/// Create a square matrix with constant diagonal entries. /// Create a square matrix with constant diagonal entries.
let inline constDiag (n: int) (f: float) = let inline constDiag (n: int) (f: float) =
let A = new DenseMatrix(n,n) let A = new DenseMatrix(n,n)
for i=0 to n-1 do for i=0 to n-1 do
A.[i,i] <- f A.[i,i] <- f
A A
/// Create a square matrix with the vector elements on the diagonal. /// Create a square matrix with the vector elements on the diagonal.
let inline diag (v: #Vector<float>) = let inline diag (v: #Vector<float>) =
let n = v.Count let n = v.Count
@ -313,26 +313,26 @@ module DenseMatrix =
/// A module which implements functional sparse vector operations. /// A module which implements functional sparse vector operations.
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module SparseMatrix = module SparseMatrix =
/// Create a matrix from a list of float lists. Every list in the master list specifies a row. /// Create a matrix from a list of float lists. Every list in the master list specifies a row.
let inline ofList (rows: int) (cols: int) (fll: list<int * int * float>) = let inline ofList (rows: int) (cols: int) (fll: list<int * int * float>) =
let A = new SparseMatrix(rows, cols) let A = new SparseMatrix(rows, cols)
fll |> List.iter (fun (i, j, x) -> A.[i,j] <- x) fll |> List.iter (fun (i, j, x) -> A.[i,j] <- x)
A A
/// Create a matrix from a list of sequences. Every sequence in the master sequence specifies a row. /// Create a matrix from a list of sequences. Every sequence in the master sequence specifies a row.
let inline ofSeq (rows: int) (cols: int) (fss: #seq<int * int * float>) = let inline ofSeq (rows: int) (cols: int) (fss: #seq<int * int * float>) =
let A = new SparseMatrix(rows, cols) let A = new SparseMatrix(rows, cols)
fss |> Seq.iter (fun (i, j, x) -> A.[i,j] <- x) fss |> Seq.iter (fun (i, j, x) -> A.[i,j] <- x)
A A
/// Create a square matrix with constant diagonal entries. /// Create a square matrix with constant diagonal entries.
let inline constDiag (n: int) (f: float) = let inline constDiag (n: int) (f: float) =
let A = new SparseMatrix(n,n) let A = new SparseMatrix(n,n)
for i=0 to n-1 do for i=0 to n-1 do
A.[i,i] <- f A.[i,i] <- f
A A
/// Create a square matrix with the vector elements on the diagonal. /// Create a square matrix with the vector elements on the diagonal.
let inline diag (v: #Vector<float>) = let inline diag (v: #Vector<float>) =
let n = v.Count let n = v.Count

50
src/FSharp/LinearAlgebra.Double.Vector.fs

@ -35,12 +35,12 @@ open MathNet.Numerics.LinearAlgebra.Generic
/// A module which implements functional vector operations. /// A module which implements functional vector operations.
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Vector = module Vector =
/// Transform a vector into an array. /// Transform a vector into an array.
let inline toArray (v: #Vector<float>) = let inline toArray (v: #Vector<float>) =
let n = v.Count let n = v.Count
Array.init n (fun i -> v.Item(i)) Array.init n (fun i -> v.Item(i))
/// Transform a vector into an array. /// Transform a vector into an array.
let inline toList (v: #Vector<float>) = let inline toList (v: #Vector<float>) =
let n = v.Count let n = v.Count
@ -57,30 +57,30 @@ module Vector =
for i=0 to v.Count-1 do for i=0 to v.Count-1 do
v.Item(i) <- f i (v.Item(i)) v.Item(i) <- f i (v.Item(i))
() ()
/// In-place vector addition. /// In-place vector addition.
let inline addInPlace (v: #Vector<float>) (w: #Vector<float>) = v.Add(w, v) let inline addInPlace (v: #Vector<float>) (w: #Vector<float>) = v.Add(w, v)
/// In place vector subtraction. /// In place vector subtraction.
let inline subInPlace (v: #Vector<float>) (w: #Vector<float>) = v.Subtract(w, v) let inline subInPlace (v: #Vector<float>) (w: #Vector<float>) = v.Subtract(w, v)
/// Functional map operator for vectors. /// Functional map operator for vectors.
/// <include file='../../../../FSharpExamples/DenseVector.xml' path='example'/> /// <include file='../../../../FSharpExamples/DenseVector.xml' path='example'/>
let inline map f (v: #Vector<float>) = let inline map f (v: #Vector<float>) =
let w = v.Clone() let w = v.Clone()
mapInPlace (fun x -> f x) w mapInPlace (fun x -> f x) w
w w
/// Applies a function to all elements of the vector. /// Applies a function to all elements of the vector.
let inline iter (f: float -> unit) (v: #Vector<float>) = let inline iter (f: float -> unit) (v: #Vector<float>) =
for i=0 to v.Count-1 do for i=0 to v.Count-1 do
f (v.Item i) f (v.Item i)
/// Applies a function to all elements of the vector. /// Applies a function to all elements of the vector.
let inline iteri (f: int -> float -> unit) (v: #Vector<float>) = let inline iteri (f: int -> float -> unit) (v: #Vector<float>) =
for i=0 to v.Count-1 do for i=0 to v.Count-1 do
f i (v.Item i) f i (v.Item i)
/// Maps a vector to a new vector by applying a function to every element. /// Maps a vector to a new vector by applying a function to every element.
let inline mapi (f: int -> float -> float) (v: #Vector<float>) = let inline mapi (f: int -> float -> float) (v: #Vector<float>) =
let w = v.Clone() let w = v.Clone()
@ -107,7 +107,7 @@ module Vector =
for i=0 to v.Count-1 do for i=0 to v.Count-1 do
acc <- f i acc (v.Item(i)) acc <- f i acc (v.Item(i))
acc acc
/// Checks whether a predicate is satisfied for every element in the vector. /// Checks whether a predicate is satisfied for every element in the vector.
let inline forall (p: float -> bool) (v: #Vector<float>) = let inline forall (p: float -> bool) (v: #Vector<float>) =
let mutable b = true let mutable b = true
@ -116,7 +116,7 @@ module Vector =
b <- b && (p (v.Item(i))) b <- b && (p (v.Item(i)))
i <- i+1 i <- i+1
b b
/// Checks whether there is an entry in the vector that satisfies a given predicate. /// Checks whether there is an entry in the vector that satisfies a given predicate.
let inline exists (p: float -> bool) (v: #Vector<float>) = let inline exists (p: float -> bool) (v: #Vector<float>) =
let mutable b = false let mutable b = false
@ -125,7 +125,7 @@ module Vector =
b <- b || (p (v.Item(i))) b <- b || (p (v.Item(i)))
i <- i+1 i <- i+1
b b
/// Checks whether a predicate is true for all entries in a vector. /// Checks whether a predicate is true for all entries in a vector.
let inline foralli (p: int -> float -> bool) (v: #Vector<float>) = let inline foralli (p: int -> float -> bool) (v: #Vector<float>) =
let mutable b = true let mutable b = true
@ -134,7 +134,7 @@ module Vector =
b <- b && (p i (v.Item(i))) b <- b && (p i (v.Item(i)))
i <- i+1 i <- i+1
b b
/// Checks whether there is an entry in the vector that satisfies a given position dependent predicate. /// Checks whether there is an entry in the vector that satisfies a given position dependent predicate.
let inline existsi (p: int -> float -> bool) (v: #Vector<float>) = let inline existsi (p: int -> float -> bool) (v: #Vector<float>) =
let mutable b = false let mutable b = false
@ -177,13 +177,13 @@ module Vector =
p p
/// Creates a new vector and inserts the given value at the given index. /// Creates a new vector and inserts the given value at the given index.
let inline insert index value (v: #Vector<float>) = let inline insert index value (v: #Vector<float>) =
let newV = new DenseVector(v.Count + 1) let newV = new DenseVector(v.Count + 1)
for i = 0 to index - 1 do for i = 0 to index - 1 do
newV.Item(i) <- v.Item(i) newV.Item(i) <- v.Item(i)
newV.Item(index) <- value newV.Item(index) <- value
for i = index + 1 to v.Count do for i = index + 1 to v.Count do
newV.Item(i) <- v.Item(i - 1) newV.Item(i) <- v.Item(i - 1)
newV newV
/// A module which implements functional dense vector operations. /// A module which implements functional dense vector operations.
@ -203,14 +203,14 @@ module DenseVector =
let v = DenseVector(n) let v = DenseVector(n)
fl |> List.iteri (fun i f -> v.[i] <- f) fl |> List.iteri (fun i f -> v.[i] <- f)
v v
/// Create a vector from a sequences. /// Create a vector from a sequences.
let inline ofSeq (fs: #seq<float>) = let inline ofSeq (fs: #seq<float>) =
let n = Seq.length fs let n = Seq.length fs
let v = DenseVector(n) let v = DenseVector(n)
fs |> Seq.iteri (fun i f -> v.[i] <- f) fs |> Seq.iteri (fun i f -> v.[i] <- f)
v v
/// Create a vector with evenly spaced entries: e.g. rangef -1.0 0.5 1.0 = [-1.0 -0.5 0.0 0.5 1.0] /// Create a vector with evenly spaced entries: e.g. rangef -1.0 0.5 1.0 = [-1.0 -0.5 0.0 0.5 1.0]
let inline rangef (start: float) (step: float) (stop: float) = let inline rangef (start: float) (step: float) (stop: float) =
let n = (int ((stop - start) / step)) + 1 let n = (int ((stop - start) / step)) + 1
@ -218,7 +218,7 @@ module DenseVector =
for i=0 to n-1 do for i=0 to n-1 do
v.[i] <- (float i) * step + start v.[i] <- (float i) * step + start
v v
/// Create a vector with integer entries in the given range. /// Create a vector with integer entries in the given range.
let inline range (start: int) (stop: int) = let inline range (start: int) (stop: int) =
new DenseVector([| for i in [start .. stop] -> float i |]) new DenseVector([| for i in [start .. stop] -> float i |])
@ -226,13 +226,13 @@ module DenseVector =
/// A module which implements functional sparse vector operations. /// A module which implements functional sparse vector operations.
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module SparseVector = module SparseVector =
/// Create a sparse vector with a given dimension from a list of entry, value pairs. /// Create a sparse vector with a given dimension from a list of entry, value pairs.
let inline ofList (dim: int) (fl: list<int * float>) = let inline ofList (dim: int) (fl: list<int * float>) =
let v = new SparseVector(dim) let v = new SparseVector(dim)
fl |> List.iter (fun (i, f) -> v.[i] <- f) fl |> List.iter (fun (i, f) -> v.[i] <- f)
v v
/// Create a sparse vector with a given dimension from a sequence of entry, value pairs. /// Create a sparse vector with a given dimension from a sequence of entry, value pairs.
let inline ofSeq (dim: int) (fs: #seq<int * float>) = let inline ofSeq (dim: int) (fs: #seq<int * float>) =
let v = new SparseVector(dim) let v = new SparseVector(dim)

18
src/FSharp/LinearAlgebra.fs

@ -33,19 +33,19 @@ namespace MathNet.Numerics.LinearAlgebra.Generic
// Module that contains implementation of useful F#-specific // Module that contains implementation of useful F#-specific
// extension members for generic Matrix and Vector types // extension members for generic Matrix and Vector types
[<AutoOpen>] [<AutoOpen>]
module FSharpExtensions = module FSharpExtensions =
// A type extension for the generic vector type that // A type extension for the generic vector type that
// adds the 'GetSlice' method to allow vec.[a .. b] syntax // adds the 'GetSlice' method to allow vec.[a .. b] syntax
type MathNet.Numerics.LinearAlgebra.Generic. type MathNet.Numerics.LinearAlgebra.Generic.
Vector<'T when 'T : struct and 'T : (new : unit -> 'T) Vector<'T when 'T : struct and 'T : (new : unit -> 'T)
and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable
and 'T :> System.ValueType> with and 'T :> System.ValueType> with
/// Gets a slice of a vector starting at a specified index /// Gets a slice of a vector starting at a specified index
/// and ending at a specified index (both indices are optional) /// and ending at a specified index (both indices are optional)
/// This method can be used via the x.[start .. finish] syntax /// This method can be used via the x.[start .. finish] syntax
member x.GetSlice(start, finish) = member x.GetSlice(start, finish) =
let start = defaultArg start 0 let start = defaultArg start 0
let finish = defaultArg finish (x.Count - 1) let finish = defaultArg finish (x.Count - 1)
x.SubVector(start, finish - start + 1) x.SubVector(start, finish - start + 1)
@ -53,14 +53,14 @@ module FSharpExtensions =
// A type extension for the generic matrix type that // A type extension for the generic matrix type that
// adds the 'GetSlice' method to allow m.[r1 .. r2, c1 .. c2] syntax // adds the 'GetSlice' method to allow m.[r1 .. r2, c1 .. c2] syntax
type MathNet.Numerics.LinearAlgebra.Generic. type MathNet.Numerics.LinearAlgebra.Generic.
Matrix<'T when 'T : struct and 'T : (new : unit -> 'T) Matrix<'T when 'T : struct and 'T : (new : unit -> 'T)
and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable and 'T :> System.IEquatable<'T> and 'T :> System.IFormattable
and 'T :> System.ValueType> with and 'T :> System.ValueType> with
/// Gets a submatrix using a specified column range and /// Gets a submatrix using a specified column range and
/// row range (all indices are optional) /// row range (all indices are optional)
/// This method can be used via the x.[r1 .. r2, c1 .. c2 ] syntax /// This method can be used via the x.[r1 .. r2, c1 .. c2 ] syntax
member x.GetSlice(rstart, rfinish, cstart, cfinish) = member x.GetSlice(rstart, rfinish, cstart, cfinish) =
let cstart = defaultArg cstart 0 let cstart = defaultArg cstart 0
let rstart = defaultArg rstart 0 let rstart = defaultArg rstart 0
let cfinish = defaultArg cfinish (x.ColumnCount - 1) let cfinish = defaultArg cfinish (x.ColumnCount - 1)

68
src/FSharp/RandomVariable.fs

@ -10,22 +10,22 @@ open MathNet.Numerics
type Outcome<'T> = { type Outcome<'T> = {
Value: 'T Value: 'T
Probability : BigRational } Probability : BigRational }
type RandomVariable<'T> = Outcome<'T> seq type RandomVariable<'T> = Outcome<'T> seq
// P(A AND B) = P(A | B) * P(B) // P(A AND B) = P(A | B) * P(B)
let private bind f dist = let private bind f dist =
dist dist
|> Seq.map (fun p1 -> |> Seq.map (fun p1 ->
f p1.Value f p1.Value
|> Seq.map (fun p2 -> |> Seq.map (fun p2 ->
{ Value = p2.Value; { Value = p2.Value;
Probability = Probability =
p1.Probability * p2.Probability})) p1.Probability * p2.Probability}))
|> Seq.concat |> Seq.concat
/// Inject a value into the RandomVariable type /// Inject a value into the RandomVariable type
let private returnM value = let private returnM value =
Seq.singleton { Value = value ; Probability = 1N/1N } Seq.singleton { Value = value ; Probability = 1N/1N }
type RandomVariableBuilder() = type RandomVariableBuilder() =
@ -35,61 +35,61 @@ type RandomVariableBuilder() =
let randomVariable = RandomVariableBuilder() let randomVariable = RandomVariableBuilder()
type CoinSide = type CoinSide =
| Heads | Heads
| Tails | Tails
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module RandomVariable = module RandomVariable =
// Create some helpers // Create some helpers
let toUniformDistribution seq = let toUniformDistribution seq =
let l = Seq.length seq let l = Seq.length seq
seq seq
|> Seq.map (fun e -> |> Seq.map (fun e ->
{ Value = e; { Value = e;
Probability = 1N / bignum.FromInt l }) Probability = 1N / bignum.FromInt l })
let probability dist = let probability dist =
dist dist
|> Seq.map (fun o -> o.Probability) |> Seq.map (fun o -> o.Probability)
|> Seq.sum |> Seq.sum
let certainly = returnM let certainly = returnM
let impossible<'a> :'a RandomVariable = toUniformDistribution [] let impossible<'a> :'a RandomVariable = toUniformDistribution []
let fairDice sides = toUniformDistribution [1..sides] let fairDice sides = toUniformDistribution [1..sides]
let fairCoin = toUniformDistribution [Heads; Tails] let fairCoin = toUniformDistribution [Heads; Tails]
let filter predicate dist = let filter predicate dist =
dist |> Seq.filter (fun o -> predicate o.Value) dist |> Seq.filter (fun o -> predicate o.Value)
let filterInAnyOrder items dist = let filterInAnyOrder items dist =
items items
|> Seq.fold (fun d item -> filter (Seq.exists ((=) (item))) d) dist |> Seq.fold (fun d item -> filter (Seq.exists ((=) (item))) d) dist
/// Transforms a RandomVariable value by using a specified mapping function. /// Transforms a RandomVariable value by using a specified mapping function.
let map f dist = let map f dist =
dist dist
|> Seq.map (fun o -> { Value = f o.Value; Probability = o.Probability }) |> Seq.map (fun o -> { Value = f o.Value; Probability = o.Probability })
let selectOne values = let selectOne values =
[for e in values -> e,values |> Seq.filter ((<>) e)] [for e in values -> e,values |> Seq.filter ((<>) e)]
|> toUniformDistribution |> toUniformDistribution
let rec selectMany n values = let rec selectMany n values =
match n with match n with
| 0 -> certainly ([],values) | 0 -> certainly ([],values)
| _ -> | _ ->
randomVariable { randomVariable {
let! (x,c1) = selectOne values let! (x,c1) = selectOne values
let! (xs,c2) = selectMany (n-1) c1 let! (xs,c2) = selectMany (n-1) c1
return x::xs,c2} return x::xs,c2}
let select n values = let select n values =
selectMany n values selectMany n values
|> map (fst >> List.rev) |> map (fst >> List.rev)
let remove items = Seq.filter (fun v -> Seq.forall ((<>) v) items) let remove items = Seq.filter (fun v -> Seq.forall ((<>) v) items)

2
src/FSharpExamples/Apply.fs

@ -90,5 +90,5 @@ for (name, fs, dotnet) in FunctionList do
if prettyPrint then printfn "\tApply.Map (MKL): %d milliseconds." sw.ElapsedMilliseconds if prettyPrint then printfn "\tApply.Map (MKL): %d milliseconds." sw.ElapsedMilliseconds
else printf "\t%d" sw.ElapsedMilliseconds else printf "\t%d" sw.ElapsedMilliseconds
sw.Reset()*) sw.Reset()*)
printfn "" printfn ""

20
src/FSharpExamples/MCMC.fs

@ -45,7 +45,7 @@ let rnd = new MersenneTwister()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
do do
printfn "Rejection Sampling Example" printfn "Rejection Sampling Example"
/// The target distribution. /// The target distribution.
let beta = new Beta(2.7, 6.3) let beta = new Beta(2.7, 6.3)
@ -76,7 +76,7 @@ do
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
do do
printfn "Metropolis Sampling Example" printfn "Metropolis Sampling Example"
let mean, stddev = 1.0, 3.5 let mean, stddev = 1.0, 3.5
let normal = new Normal(mean, stddev) let normal = new Normal(mean, stddev)
@ -93,7 +93,7 @@ do
printfn "\tEmpirical StdDev = %f (should be %f)" (Statistics.StandardDeviation(arr)) normal.StdDev printfn "\tEmpirical StdDev = %f (should be %f)" (Statistics.StandardDeviation(arr)) normal.StdDev
printfn "\tAcceptance rate = %f" ms.AcceptanceRate printfn "\tAcceptance rate = %f" ms.AcceptanceRate
printfn "" printfn ""
// //
@ -107,12 +107,12 @@ do
printfn "Metropolis Hastings Sampling Example (Symmetric Proposal)" printfn "Metropolis Hastings Sampling Example (Symmetric Proposal)"
let mean, stddev = 1.0, 3.5 let mean, stddev = 1.0, 3.5
let normal = new Normal(mean, stddev) let normal = new Normal(mean, stddev)
/// Evaluates the log normal distribution. /// Evaluates the log normal distribution.
let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) - 0.5 * log(2.0 * System.Math.PI * s * s) let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) - 0.5 * log(2.0 * System.Math.PI * s * s)
/// Implements the rejection sampling procedure. /// Implements the rejection sampling procedure.
let ms = new MetropolisHastingsSampler<float>( 0.1, (fun x -> log(normal.Density(x))), let ms = new MetropolisHastingsSampler<float>( 0.1, (fun x -> log(normal.Density(x))),
(fun x y -> npdf x y 0.3), (fun x -> Normal.Sample(rnd, x, 0.3)), 10, (fun x y -> npdf x y 0.3), (fun x -> Normal.Sample(rnd, x, 0.3)), 10,
RandomSource = rnd ) RandomSource = rnd )
@ -138,22 +138,22 @@ do
printfn "Metropolis Hastings Sampling Example (Assymetric Proposal)" printfn "Metropolis Hastings Sampling Example (Assymetric Proposal)"
let mean, stddev = 1.0, 3.5 let mean, stddev = 1.0, 3.5
let normal = new Normal(mean, stddev) let normal = new Normal(mean, stddev)
/// Evaluates the logarithm of the normal distribution function. /// Evaluates the logarithm of the normal distribution function.
let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) - 0.5 * log(2.0 * System.Math.PI * s * s) let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) - 0.5 * log(2.0 * System.Math.PI * s * s)
/// Samples from a mixture that is biased towards samples larger than x. /// Samples from a mixture that is biased towards samples larger than x.
let mixSample x = let mixSample x =
if Bernoulli.Sample(rnd, 0.5) = 1 then if Bernoulli.Sample(rnd, 0.5) = 1 then
Normal.Sample(rnd, x, 0.3) Normal.Sample(rnd, x, 0.3)
else else
Normal.Sample(rnd, x + 0.1, 0.3) Normal.Sample(rnd, x + 0.1, 0.3)
/// The transition kernel for the proposal above. /// The transition kernel for the proposal above.
let krnl xnew x = log (0.5 * exp(npdf xnew x 0.3) + 0.5 * exp(npdf xnew (x+0.1) 0.3)) let krnl xnew x = log (0.5 * exp(npdf xnew x 0.3) + 0.5 * exp(npdf xnew (x+0.1) 0.3))
/// Implements the rejection sampling procedure. /// Implements the rejection sampling procedure.
let ms = new MetropolisHastingsSampler<float>( 0.1, (fun x -> log(normal.Density(x))), let ms = new MetropolisHastingsSampler<float>( 0.1, (fun x -> log(normal.Density(x))),
(fun xnew x -> krnl xnew x), (fun x -> mixSample x), 10, (fun xnew x -> krnl xnew x), (fun x -> mixSample x), 10,
RandomSource = rnd ) RandomSource = rnd )
@ -178,7 +178,7 @@ do
printfn "Slice Sampling Example" printfn "Slice Sampling Example"
let mean, stddev = 1.0, 3.5 let mean, stddev = 1.0, 3.5
let normal = new Normal(mean, stddev) let normal = new Normal(mean, stddev)
/// Evaluates the unnormalized logarithm of the normal distribution function. /// Evaluates the unnormalized logarithm of the normal distribution function.
let npdf x m s = -0.5*(x-m)*(x-m)/(s*s) let npdf x m s = -0.5*(x-m)*(x-m)/(s*s)

274
src/FSharpUnitTests/BigRationalTests.fs

@ -1,4 +1,4 @@
// First version copied from the F# Power Pack // First version copied from the F# Power Pack
// https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack.Unittests/BigRationalTests.fs // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack.Unittests/BigRationalTests.fs
namespace MathNet.Numerics.Tests namespace MathNet.Numerics.Tests
@ -69,14 +69,14 @@ type public BigRationalTests() =
points points
let pointsNonZero = [for p,q in points do if p<>0I then yield p,q] // non zero points let pointsNonZero = [for p,q in points do if p<>0I then yield p,q] // non zero points
let makeQs p q = let makeQs p q =
if q = 1I && minIntI <= p && p <= maxIntI then if q = 1I && minIntI <= p && p <= maxIntI then
// (p,1) where p is int32 // (p,1) where p is int32
let p32 = int32 p let p32 = int32 p
[natA p32;natB p32;BigRational.FromBigInt p] // two reprs for int32 [natA p32;natB p32;BigRational.FromBigInt p] // two reprs for int32
else else
[BigRational.FromBigInt p / BigRational.FromBigInt q] [BigRational.FromBigInt p / BigRational.FromBigInt q]
let miscQs = [for p,q in points do yield! makeQs p q] let miscQs = [for p,q in points do yield! makeQs p q]
let product xs ys = [for x in xs do for y in ys do yield x,y] let product xs ys = [for x in xs do for y in ys do yield x,y]
@ -84,7 +84,7 @@ type public BigRationalTests() =
let vector2s = product points points let vector2s = product points points
[<Test>] [<Test>]
member this.BasicTests1() = member this.BasicTests1() =
check "generic format h" "1N" (sprintf "%A" 1N) check "generic format h" "1N" (sprintf "%A" 1N)
check "generic format q" "-1N" (sprintf "%A" (-1N)) check "generic format q" "-1N" (sprintf "%A" (-1N))
@ -92,7 +92,7 @@ type public BigRationalTests() =
test "d3oc002" (LanguagePrimitives.GenericZero<bignum> = 0N) test "d3oc002" (LanguagePrimitives.GenericZero<bignum> = 0N)
test "d3oc112w" (LanguagePrimitives.GenericOne<bignum> = 1N) test "d3oc112w" (LanguagePrimitives.GenericOne<bignum> = 1N)
check "weioj3h" (sprintf "%O" 3N) "3" check "weioj3h" (sprintf "%O" 3N) "3"
check "weioj3k" (sprintf "%O" (3N / 4N)) "3/4" check "weioj3k" (sprintf "%O" (3N / 4N)) "3/4"
check "weioj3k" (sprintf "%O" (3N / 400000000N)) "3/400000000" check "weioj3k" (sprintf "%O" (3N / 400000000N)) "3/400000000"
check "weioj3l" (sprintf "%O" (3N / 3N)) "1" check "weioj3l" (sprintf "%O" (3N / 3N)) "1"
@ -105,21 +105,21 @@ type public BigRationalTests() =
let v = -30000000000000000000000000000000000000000000000000000000000000N let v = -30000000000000000000000000000000000000000000000000000000000000N
check "weioj3r" (sprintf "%O" v) ((box v).ToString()) check "weioj3r" (sprintf "%O" v) ((box v).ToString())
[<Test>] [<Test>]
member this.BasicTests2() = member this.BasicTests2() =
// Test arithmetic ops: tests // Test arithmetic ops: tests
let test2One name f check ((p,q),(pp,qq)) = let test2One name f check ((p,q),(pp,qq)) =
// There may be several ways to construct the test rationals // There may be several ways to construct the test rationals
let zs = makeQs p q let zs = makeQs p q
let zzs = makeQs pp qq let zzs = makeQs pp qq
let results = [for z in zs do for zz in zzs do yield f (z,zz)] let results = [for z in zs do for zz in zzs do yield f (z,zz)]
let refP,refQ = check (p,q) (pp,qq) let refP,refQ = check (p,q) (pp,qq)
let refResult = BigRational.FromBigInt refP / BigRational.FromBigInt refQ let refResult = BigRational.FromBigInt refP / BigRational.FromBigInt refQ
let resOK (result:BigRational) = let resOK (result:BigRational) =
result.Numerator * refQ = refP * result.Denominator && result.Numerator * refQ = refP * result.Denominator &&
BigRational.Equals(refResult,result) BigRational.Equals(refResult,result)
match List.tryFind (fun result -> not (resOK result)) results with match List.tryFind (fun result -> not (resOK result)) results with
| None -> () // ok | None -> () // ok
@ -135,9 +135,9 @@ type public BigRationalTests() =
test2All "div" (BigRational.(/)) (fun (p,q) (pp,qq) -> (p*qq,q*pp)) (product points pointsNonZero) test2All "div" (BigRational.(/)) (fun (p,q) (pp,qq) -> (p*qq,q*pp)) (product points pointsNonZero)
[<Test>] [<Test>]
member this.RangeTests() = member this.RangeTests() =
// Test x0 .. dx .. x1 // Test x0 .. dx .. x1
let checkRange3 (x0:BigRational) dx x1 k = let checkRange3 (x0:BigRational) dx x1 k =
let f (x:BigRational) = x * BigRational.FromBigInt k |> BigRational.ToBigInt let f (x:BigRational) = x * BigRational.FromBigInt k |> BigRational.ToBigInt
@ -146,7 +146,7 @@ type public BigRationalTests() =
//printf "Length=%d\n" (Seq.length rangeA) //printf "Length=%d\n" (Seq.length rangeA)
let same = Seq.forall2 (=) rangeA rangeB let same = Seq.forall2 (=) rangeA rangeB
check (sprintf "Range3 %A .. %A .. %A scaled to %A" x0 dx x1 k) same true check (sprintf "Range3 %A .. %A .. %A scaled to %A" x0 dx x1 k) same true
checkRange3 (0I /% 1I) (1I /% 7I) (100I /% 1I) (7I*1I) checkRange3 (0I /% 1I) (1I /% 7I) (100I /% 1I) (7I*1I)
checkRange3 (0I /% 1I) (1I /% 7I) (100I /% 11I) (7I*11I) checkRange3 (0I /% 1I) (1I /% 7I) (100I /% 11I) (7I*11I)
checkRange3 (1I /% 13I) (1I /% 7I) (100I /% 11I) (7I*11I*13I) checkRange3 (1I /% 13I) (1I /% 7I) (100I /% 11I) (7I*11I*13I)
@ -161,15 +161,15 @@ type public BigRationalTests() =
// Test x0 .. x1 // Test x0 .. x1
let checkRange2 (x0:BigRational) x1 = let checkRange2 (x0:BigRational) x1 =
let z0 = BigRational.ToBigInt x0 let z0 = BigRational.ToBigInt x0
let z01 = BigRational.ToBigInt (x1 - x0) let z01 = BigRational.ToBigInt (x1 - x0)
let f (x:BigRational) = x |> BigRational.ToBigInt let f (x:BigRational) = x |> BigRational.ToBigInt
let rangeA = [x0 .. x1] |> List.map f // range with each item rounded down let rangeA = [x0 .. x1] |> List.map f // range with each item rounded down
let rangeB = [z0 .. z0 + z01] // range of same length from the round down start point let rangeB = [z0 .. z0 + z01] // range of same length from the round down start point
check (sprintf "Range2: %A .. %A" x0 x1) rangeA rangeB check (sprintf "Range2: %A .. %A" x0 x1) rangeA rangeB
checkRange2 (0I /% 1I) (100I /% 1I) checkRange2 (0I /% 1I) (100I /% 1I)
checkRange2 (0I /% 1I) (100I /% 11I) checkRange2 (0I /% 1I) (100I /% 11I)
checkRange2 (1I /% 13I) (100I /% 11I) checkRange2 (1I /% 13I) (100I /% 11I)
for i = 0 to 1000 do for i = 0 to 1000 do
let m = 10000 // max steps is -m to m in steps of 1 i.e. 2.m let m = 10000 // max steps is -m to m in steps of 1 i.e. 2.m
let p0,q0 = nextZ m ,nextZ m + 1I let p0,q0 = nextZ m ,nextZ m + 1I
@ -178,7 +178,7 @@ type public BigRationalTests() =
// ToString() // ToString()
// Cases: integer, computed integer, rational<1, rational>1, +/-infinity, nan // Cases: integer, computed integer, rational<1, rational>1, +/-infinity, nan
(natA 1).ToString() |> check "ToString" "1" (natA 1).ToString() |> check "ToString" "1"
(natA 0).ToString() |> check "ToString" "0" (natA 0).ToString() |> check "ToString" "0"
(natA (-12)).ToString() |> check "ToString" "-12" (natA (-12)).ToString() |> check "ToString" "-12"
(natB 1).ToString() |> check "ToString" "1" (natB 1).ToString() |> check "ToString" "1"
@ -211,29 +211,29 @@ type public BigRationalTests() =
check "OneB" BigRational.One (natB 1) check "OneB" BigRational.One (natB 1)
[<Test>] [<Test>]
member this.BinaryAndUnaryOperators() = member this.BinaryAndUnaryOperators() =
// Test: generic bop // Test: generic bop
let testR2One name f check ((p,q),(pp,qq)) = let testR2One name f check ((p,q),(pp,qq)) =
// There may be several ways to construct the test rationals // There may be several ways to construct the test rationals
let zs = makeQs p q let zs = makeQs p q
let zzs = makeQs pp qq let zzs = makeQs pp qq
let resultRef = check (p,q) (pp,qq) // : bool let resultRef = check (p,q) (pp,qq) // : bool
let args = [for z in zs do for zz in zzs do yield (z,zz)] let args = [for z in zs do for zz in zzs do yield (z,zz)]
match List.tryFind (fun (z,zz) -> resultRef <> f (z,zz)) args with match List.tryFind (fun (z,zz) -> resultRef <> f (z,zz)) args with
| None -> () // ok | None -> () // ok
| Some (z,zz) -> printf "Test failed. %s (%A,%A) (%A,%A) = %s %A %A. Expected %A.\n" name p q pp qq name z zz resultRef | Some (z,zz) -> printf "Test failed. %s (%A,%A) (%A,%A) = %s %A %A. Expected %A.\n" name p q pp qq name z zz resultRef
reportFailure "cknwe9" reportFailure "cknwe9"
// Test: generic uop // Test: generic uop
let testR1One name f check (p,q) = let testR1One name f check (p,q) =
// There may be several ways to construct the test rationals // There may be several ways to construct the test rationals
let zs = makeQs p q let zs = makeQs p q
let resultRef = check (p,q) //: bool let resultRef = check (p,q) //: bool
match List.tryFind (fun z -> resultRef <> f z) zs with match List.tryFind (fun z -> resultRef <> f z) zs with
| None -> () // ok | None -> () // ok
| Some z -> printf "Test failed. %s (%A,%A) = %s %A. Expected %A.\n" name p q name z resultRef | Some z -> printf "Test failed. %s (%A,%A) = %s %A. Expected %A.\n" name p q name z resultRef
reportFailure "vekjkrejvre0" reportFailure "vekjkrejvre0"
let testR2All name f check vectors = List.iter (testR2One name f check) vectors let testR2All name f check vectors = List.iter (testR2One name f check) vectors
let testR1All name f check vectors = List.iter (testR1One name f check) vectors let testR1All name f check vectors = List.iter (testR1One name f check) vectors
@ -260,14 +260,14 @@ type public BigRationalTests() =
testR1All "IsZero" (fun (x:BigRational) -> x = q0) (fun (p,q) -> sign p = 0I) vector1s testR1All "IsZero" (fun (x:BigRational) -> x = q0) (fun (p,q) -> sign p = 0I) vector1s
let test1One name f check (p,q) = let test1One name f check (p,q) =
// There may be several ways to construct the test rationals // There may be several ways to construct the test rationals
let zs = makeQs p q let zs = makeQs p q
let results = [for z in zs -> f z] let results = [for z in zs -> f z]
let refP,refQ = check (p,q) let refP,refQ = check (p,q)
let refResult = BigRational.FromBigInt refP / BigRational.FromBigInt refQ let refResult = BigRational.FromBigInt refP / BigRational.FromBigInt refQ
let resOK (result:BigRational) = let resOK (result:BigRational) =
result.Numerator * refQ = refP * result.Denominator && result.Numerator * refQ = refP * result.Denominator &&
BigRational.Equals(refResult,result) BigRational.Equals(refResult,result)
match List.tryFind (fun result -> not (resOK result)) results with match List.tryFind (fun result -> not (resOK result)) results with
| None -> () // ok | None -> () // ok
@ -275,7 +275,7 @@ type public BigRationalTests() =
reportFailure "klcwe09wek" reportFailure "klcwe09wek"
let test1All name f check vectors = List.iter (test1One name f check) vectors let test1All name f check vectors = List.iter (test1One name f check) vectors
test1All "neg" (BigRational.(~-)) (fun (p,q) -> (-p,q)) vector1s test1All "neg" (BigRational.(~-)) (fun (p,q) -> (-p,q)) vector1s
test1All "pos" (BigRational.(~+)) (fun (p,q) -> (p,q)) vector1s // why have ~+ ??? test1All "pos" (BigRational.(~+)) (fun (p,q) -> (p,q)) vector1s // why have ~+ ???
@ -312,27 +312,27 @@ type BigNumType() =
let g_normal = 88N let g_normal = 88N
let g_bigintpositive = 1000000000000000000000000000000000018I let g_bigintpositive = 1000000000000000000000000000000000018I
let g_bigintnegative = -1000000000000000000000000000000000018I let g_bigintnegative = -1000000000000000000000000000000000018I
// Interfaces // Interfaces
[<Test>] [<Test>]
member this.IComparable() = member this.IComparable() =
// Legit IC // Legit IC
let ic = g_positive1 :> IComparable let ic = g_positive1 :> IComparable
Assert.AreEqual(ic.CompareTo(g_positive1),0) Assert.AreEqual(ic.CompareTo(g_positive1),0)
checkThrowsArgumentException( fun () -> ic.CompareTo(g_bigintpositive) |> ignore) checkThrowsArgumentException( fun () -> ic.CompareTo(g_bigintpositive) |> ignore)
// Base class methods // Base class methods
[<Test>] [<Test>]
member this.ObjectToString() = member this.ObjectToString() =
// Currently the CLR 4.0 and CLR 2.0 behavior of BigInt.ToString is different, causing this test to fail. // Currently the CLR 4.0 and CLR 2.0 behavior of BigInt.ToString is different, causing this test to fail.
Assert.AreEqual(g_positive1.ToString(), Assert.AreEqual(g_positive1.ToString(),
"1000000000000000000000000000000000018") "1000000000000000000000000000000000018")
Assert.AreEqual(g_zero.ToString(),"0") Assert.AreEqual(g_zero.ToString(),"0")
Assert.AreEqual(g_normal.ToString(),"88") Assert.AreEqual(g_normal.ToString(),"88")
// Static methods // Static methods
[<Test>] [<Test>]
member this.Abs() = member this.Abs() =
Assert.AreEqual(bignum.Abs(g_negative1), g_positive1) Assert.AreEqual(bignum.Abs(g_negative1), g_positive1)
@ -341,7 +341,7 @@ type BigNumType() =
Assert.AreEqual(bignum.Abs(g_normal), g_normal) Assert.AreEqual(bignum.Abs(g_normal), g_normal)
Assert.AreEqual(bignum.Abs(g_zero), g_zero) Assert.AreEqual(bignum.Abs(g_zero), g_zero)
() ()
[<Test>] [<Test>]
member this.FromBigInt() = member this.FromBigInt() =
Assert.AreEqual(bignum.FromBigInt(g_bigintpositive), Assert.AreEqual(bignum.FromBigInt(g_bigintpositive),
@ -351,7 +351,7 @@ type BigNumType() =
Assert.AreEqual(bignum.FromBigInt(0I),g_zero) Assert.AreEqual(bignum.FromBigInt(0I),g_zero)
Assert.AreEqual(bignum.FromBigInt(88I),g_normal) Assert.AreEqual(bignum.FromBigInt(88I),g_normal)
() ()
[<Test>] [<Test>]
member this.FromInt() = member this.FromInt() =
Assert.AreEqual(bignum.FromInt(2147483647), 2147483647N) Assert.AreEqual(bignum.FromInt(2147483647), 2147483647N)
@ -359,12 +359,12 @@ type BigNumType() =
Assert.AreEqual(bignum.FromInt(0), 0N) Assert.AreEqual(bignum.FromInt(0), 0N)
Assert.AreEqual(bignum.FromInt(88), 88N) Assert.AreEqual(bignum.FromInt(88), 88N)
() ()
[<Test>] [<Test>]
member this.One() = member this.One() =
Assert.AreEqual(bignum.One,1N) Assert.AreEqual(bignum.One,1N)
() ()
[<Test>] [<Test>]
member this.Parse() = member this.Parse() =
Assert.AreEqual(bignum.Parse("100"), 100N) Assert.AreEqual(bignum.Parse("100"), 100N)
@ -372,7 +372,7 @@ type BigNumType() =
Assert.AreEqual(bignum.Parse("0"), g_zero) Assert.AreEqual(bignum.Parse("0"), g_zero)
Assert.AreEqual(bignum.Parse("88"), g_normal) Assert.AreEqual(bignum.Parse("88"), g_normal)
() ()
[<Test>] [<Test>]
member this.PowN() = member this.PowN() =
Assert.AreEqual(bignum.PowN(100N,2), 10000N) Assert.AreEqual(bignum.PowN(100N,2), 10000N)
@ -380,8 +380,8 @@ type BigNumType() =
Assert.AreEqual(bignum.PowN(g_zero,2147483647), 0N) Assert.AreEqual(bignum.PowN(g_zero,2147483647), 0N)
Assert.AreEqual(bignum.PowN(g_normal,0), 1N) Assert.AreEqual(bignum.PowN(g_normal,0), 1N)
() ()
[<Test>] [<Test>]
member this.Sign() = member this.Sign() =
Assert.AreEqual(g_positive1.Sign, 1) Assert.AreEqual(g_positive1.Sign, 1)
@ -389,9 +389,9 @@ type BigNumType() =
Assert.AreEqual(g_zero.Sign, 0) Assert.AreEqual(g_zero.Sign, 0)
Assert.AreEqual(g_normal.Sign, 1) Assert.AreEqual(g_normal.Sign, 1)
() ()
[<Test>] [<Test>]
member this.ToBigInt() = member this.ToBigInt() =
Assert.AreEqual(bignum.ToBigInt(g_positive1), g_bigintpositive) Assert.AreEqual(bignum.ToBigInt(g_positive1), g_bigintpositive)
@ -399,9 +399,9 @@ type BigNumType() =
Assert.AreEqual(bignum.ToBigInt(g_zero), 0I) Assert.AreEqual(bignum.ToBigInt(g_zero), 0I)
Assert.AreEqual(bignum.ToBigInt(g_normal), 88I) Assert.AreEqual(bignum.ToBigInt(g_normal), 88I)
() ()
[<Test>] [<Test>]
member this.ToDouble() = member this.ToDouble() =
Assert.AreEqual(bignum.ToDouble(179769N*1000000000000000N), 1.79769E+20) Assert.AreEqual(bignum.ToDouble(179769N*1000000000000000N), 1.79769E+20)
@ -413,8 +413,8 @@ type BigNumType() =
Assert.AreEqual(double(0N),0.0) Assert.AreEqual(double(0N),0.0)
Assert.AreEqual(double(88N),88.0) Assert.AreEqual(double(88N),88.0)
() ()
[<Test>] [<Test>]
member this.ToInt32() = member this.ToInt32() =
Assert.AreEqual(bignum.ToInt32(2147483647N), 2147483647) Assert.AreEqual(bignum.ToInt32(2147483647N), 2147483647)
@ -425,18 +425,18 @@ type BigNumType() =
Assert.AreEqual(int32(-2147483648N), -2147483648) Assert.AreEqual(int32(-2147483648N), -2147483648)
Assert.AreEqual(int32(0N), 0) Assert.AreEqual(int32(0N), 0)
Assert.AreEqual(int32(88N), 88) Assert.AreEqual(int32(88N), 88)
[<Test>] [<Test>]
member this.Zero() = member this.Zero() =
Assert.AreEqual(bignum.Zero,0N) Assert.AreEqual(bignum.Zero,0N)
() ()
// operator methods // operator methods
[<Test>] [<Test>]
member this.test_op_Addition() = member this.test_op_Addition() =
Assert.AreEqual(100N + 200N, 300N) Assert.AreEqual(100N + 200N, 300N)
Assert.AreEqual((-100N) + (-200N), -300N) Assert.AreEqual((-100N) + (-200N), -300N)
Assert.AreEqual(g_positive1 + g_negative1, 0N) Assert.AreEqual(g_positive1 + g_negative1, 0N)
@ -444,163 +444,163 @@ type BigNumType() =
Assert.AreEqual(g_normal + g_normal, 176N) Assert.AreEqual(g_normal + g_normal, 176N)
Assert.AreEqual(g_normal + g_normal, 176N) Assert.AreEqual(g_normal + g_normal, 176N)
() ()
[<Test>] [<Test>]
member this.test_op_Division() = member this.test_op_Division() =
Assert.AreEqual(g_positive1 / g_positive1, 1N) Assert.AreEqual(g_positive1 / g_positive1, 1N)
Assert.AreEqual(-100N / 2N, -50N) Assert.AreEqual(-100N / 2N, -50N)
Assert.AreEqual(g_zero / g_positive1, 0N) Assert.AreEqual(g_zero / g_positive1, 0N)
() ()
[<Test>] [<Test>]
member this.test_op_Equality() = member this.test_op_Equality() =
Assert.IsTrue((g_positive1 = g_positive1)) Assert.IsTrue((g_positive1 = g_positive1))
Assert.IsTrue((g_negative1 = g_negative1)) Assert.IsTrue((g_negative1 = g_negative1))
Assert.IsTrue((g_zero = g_zero)) Assert.IsTrue((g_zero = g_zero))
Assert.IsTrue((g_normal = g_normal)) Assert.IsTrue((g_normal = g_normal))
() ()
[<Test>] [<Test>]
member this.test_op_GreaterThan() = member this.test_op_GreaterThan() =
Assert.AreEqual((g_positive1 > g_positive2), true) Assert.AreEqual((g_positive1 > g_positive2), true)
Assert.AreEqual((g_negative1 > g_negative2), false) Assert.AreEqual((g_negative1 > g_negative2), false)
Assert.AreEqual((g_zero > g_zero), false) Assert.AreEqual((g_zero > g_zero), false)
Assert.AreEqual((g_normal > g_normal), false) Assert.AreEqual((g_normal > g_normal), false)
() ()
[<Test>] [<Test>]
member this.test_op_GreaterThanOrEqual() = member this.test_op_GreaterThanOrEqual() =
Assert.AreEqual((g_positive1 >= g_positive2), true) Assert.AreEqual((g_positive1 >= g_positive2), true)
Assert.AreEqual((g_positive2 >= g_positive1), false) Assert.AreEqual((g_positive2 >= g_positive1), false)
Assert.AreEqual((g_negative1 >= g_negative1), true) Assert.AreEqual((g_negative1 >= g_negative1), true)
Assert.AreEqual((0N >= g_zero), true) Assert.AreEqual((0N >= g_zero), true)
() ()
[<Test>] [<Test>]
member this.test_op_LessThan() = member this.test_op_LessThan() =
Assert.AreEqual((g_positive1 < g_positive2), false) Assert.AreEqual((g_positive1 < g_positive2), false)
Assert.AreEqual((g_negative1 < g_negative3), false) Assert.AreEqual((g_negative1 < g_negative3), false)
Assert.AreEqual((0N < g_zero), false) Assert.AreEqual((0N < g_zero), false)
() ()
[<Test>] [<Test>]
member this.test_op_LessThanOrEqual() = member this.test_op_LessThanOrEqual() =
Assert.AreEqual((g_positive1 <= g_positive2), false) Assert.AreEqual((g_positive1 <= g_positive2), false)
Assert.AreEqual((g_positive2 <= g_positive1), true) Assert.AreEqual((g_positive2 <= g_positive1), true)
Assert.AreEqual((g_negative1 <= g_negative1), true) Assert.AreEqual((g_negative1 <= g_negative1), true)
Assert.AreEqual((0N <= g_zero), true) Assert.AreEqual((0N <= g_zero), true)
() ()
[<Test>] [<Test>]
member this.test_op_Multiply() = member this.test_op_Multiply() =
Assert.AreEqual(3N * 5N, 15N) Assert.AreEqual(3N * 5N, 15N)
Assert.AreEqual((-3N) * (-5N), 15N) Assert.AreEqual((-3N) * (-5N), 15N)
Assert.AreEqual((-3N) * 5N, -15N) Assert.AreEqual((-3N) * 5N, -15N)
Assert.AreEqual(0N * 5N, 0N) Assert.AreEqual(0N * 5N, 0N)
() ()
[<Test>] [<Test>]
member this.test_op_Range() = member this.test_op_Range() =
let resultPos = [0N .. 2N] let resultPos = [0N .. 2N]
let seqPos = [0N; 1N; 2N] let seqPos = [0N; 1N; 2N]
verifySeqsEqual resultPos seqPos verifySeqsEqual resultPos seqPos
let resultNeg = [-2N .. 0N] let resultNeg = [-2N .. 0N]
let seqNeg = [-2N; -1N; 0N] let seqNeg = [-2N; -1N; 0N]
verifySeqsEqual resultNeg seqNeg verifySeqsEqual resultNeg seqNeg
let resultSmall = [0N ..5N] let resultSmall = [0N ..5N]
let seqSmall = [0N; 1N; 2N; 3N; 4N; 5N] let seqSmall = [0N; 1N; 2N; 3N; 4N; 5N]
verifySeqsEqual resultSmall seqSmall verifySeqsEqual resultSmall seqSmall
() ()
[<Test>] [<Test>]
member this.test_op_RangeStep() = member this.test_op_RangeStep() =
let resultPos = [0N .. 3N .. 6N] let resultPos = [0N .. 3N .. 6N]
let seqPos = [0N; 3N; 6N] let seqPos = [0N; 3N; 6N]
verifySeqsEqual resultPos seqPos verifySeqsEqual resultPos seqPos
let resultNeg = [-6N .. 3N .. 0N] let resultNeg = [-6N .. 3N .. 0N]
let seqNeg = [-6N; -3N; 0N] let seqNeg = [-6N; -3N; 0N]
verifySeqsEqual resultNeg seqNeg verifySeqsEqual resultNeg seqNeg
let resultSmall = [0N .. 3N .. 9N] let resultSmall = [0N .. 3N .. 9N]
let seqSmall = [0N; 3N; 6N; 9N] let seqSmall = [0N; 3N; 6N; 9N]
verifySeqsEqual resultSmall seqSmall verifySeqsEqual resultSmall seqSmall
() ()
[<Test>] [<Test>]
member this.test_op_Subtraction() = member this.test_op_Subtraction() =
Assert.AreEqual(g_positive1 - g_positive2,18N) Assert.AreEqual(g_positive1 - g_positive2,18N)
Assert.AreEqual(g_negative1 - g_negative3,18N) Assert.AreEqual(g_negative1 - g_negative3,18N)
Assert.AreEqual(0N-g_positive1, g_negative1) Assert.AreEqual(0N-g_positive1, g_negative1)
() ()
[<Test>] [<Test>]
member this.test_op_UnaryNegation() = member this.test_op_UnaryNegation() =
Assert.AreEqual(-g_positive1, g_negative1) Assert.AreEqual(-g_positive1, g_negative1)
Assert.AreEqual(-g_negative1, g_positive1) Assert.AreEqual(-g_negative1, g_positive1)
Assert.AreEqual(-0N,0N) Assert.AreEqual(-0N,0N)
() ()
[<Test>] [<Test>]
member this.test_op_UnaryPlus() = member this.test_op_UnaryPlus() =
Assert.AreEqual(+g_positive1,g_positive1) Assert.AreEqual(+g_positive1,g_positive1)
Assert.AreEqual(+g_negative1,g_negative1) Assert.AreEqual(+g_negative1,g_negative1)
Assert.AreEqual(+0N, 0N) Assert.AreEqual(+0N, 0N)
() ()
// instance methods // instance methods
[<Test>] [<Test>]
member this.Denominator() = member this.Denominator() =
Assert.AreEqual(g_positive1.Denominator, 1I) Assert.AreEqual(g_positive1.Denominator, 1I)
Assert.AreEqual(g_negative1.Denominator, 1I) Assert.AreEqual(g_negative1.Denominator, 1I)
Assert.AreEqual(0N.Denominator, 1I) Assert.AreEqual(0N.Denominator, 1I)
() ()
[<Test>] [<Test>]
member this.IsNegative() = member this.IsNegative() =
Assert.IsFalse(g_positive1.IsNegative) Assert.IsFalse(g_positive1.IsNegative)
Assert.IsTrue(g_negative1.IsNegative) Assert.IsTrue(g_negative1.IsNegative)
Assert.IsFalse( 0N.IsNegative) Assert.IsFalse( 0N.IsNegative)
Assert.IsFalse(-0N.IsNegative) Assert.IsFalse(-0N.IsNegative)
() ()
[<Test>] [<Test>]
member this.IsPositive() = member this.IsPositive() =
Assert.IsTrue(g_positive1.IsPositive) Assert.IsTrue(g_positive1.IsPositive)
Assert.IsFalse(g_negative1.IsPositive) Assert.IsFalse(g_negative1.IsPositive)
Assert.IsFalse( 0N.IsPositive) Assert.IsFalse( 0N.IsPositive)
Assert.IsFalse(-0N.IsPositive) Assert.IsFalse(-0N.IsPositive)
() ()
[<Test>] [<Test>]
member this.Numerator() = member this.Numerator() =
Assert.AreEqual(g_positive1.Numerator, g_bigintpositive) Assert.AreEqual(g_positive1.Numerator, g_bigintpositive)
Assert.AreEqual(g_negative1.Numerator, g_bigintnegative) Assert.AreEqual(g_negative1.Numerator, g_bigintnegative)
Assert.AreEqual(0N.Numerator, 0I) Assert.AreEqual(0N.Numerator, 0I)
() ()

42
src/FSharpUnitTests/DenseMatrixTests.fs

@ -13,39 +13,39 @@ module DenseMatrixTests =
/// A large vector with increasingly large entries /// A large vector with increasingly large entries
let largeM = new DenseMatrix( Array2D.init 100 100 (fun i j -> float i * 100.0 + float j) ) let largeM = new DenseMatrix( Array2D.init 100 100 (fun i j -> float i * 100.0 + float j) )
[<Test>] [<Test>]
let ``DenseMatrix.init`` () = let ``DenseMatrix.init`` () =
DenseMatrix.init 100 100 (fun i j -> float i * 100.0 + float j) |> should equal largeM DenseMatrix.init 100 100 (fun i j -> float i * 100.0 + float j) |> should equal largeM
[<Test>] [<Test>]
let ``DenseMatrix.ofList`` () = let ``DenseMatrix.ofList`` () =
DenseMatrix.ofList [[0.3;0.3];[0.3;0.3]] |> should equal smallM DenseMatrix.ofList [[0.3;0.3];[0.3;0.3]] |> should equal smallM
[<Test>] [<Test>]
let ``DenseMatrix.ofSeq`` () = let ``DenseMatrix.ofSeq`` () =
DenseMatrix.ofSeq (Seq.ofList [[0.3;0.3];[0.3;0.3]]) |> should equal smallM DenseMatrix.ofSeq (Seq.ofList [[0.3;0.3];[0.3;0.3]]) |> should equal smallM
[<Test>] [<Test>]
let ``DenseMatrix.ofArray2`` () = let ``DenseMatrix.ofArray2`` () =
DenseMatrix.ofArray2 (Array2D.create 2 2 0.3) |> should equal smallM DenseMatrix.ofArray2 (Array2D.create 2 2 0.3) |> should equal smallM
[<Test>] [<Test>]
let ``DenseMatrix.initDense`` () = let ``DenseMatrix.initDense`` () =
DenseMatrix.initDense 100 100 (seq { for i in 0 .. 99 do DenseMatrix.initDense 100 100 (seq { for i in 0 .. 99 do
for j in 0 .. 99 -> (i,j, float i * 100.0 + float j)}) |> should equal largeM for j in 0 .. 99 -> (i,j, float i * 100.0 + float j)}) |> should equal largeM
[<Test>] [<Test>]
let ``DenseMatrix.constDiag`` () = let ``DenseMatrix.constDiag`` () =
DenseMatrix.constDiag 100 2.0 |> should equal (2.0 * (DenseMatrix.Identity 100)) DenseMatrix.constDiag 100 2.0 |> should equal (2.0 * (DenseMatrix.Identity 100))
[<Test>] [<Test>]
let ``DenseMatrix.diag`` () = let ``DenseMatrix.diag`` () =
DenseMatrix.diag (new DenseVector(100, 2.0)) |> should equal (2.0 * (DenseMatrix.Identity 100)) DenseMatrix.diag (new DenseVector(100, 2.0)) |> should equal (2.0 * (DenseMatrix.Identity 100))
[<Test>] [<Test>]
let ``DenseMatrix.init_row`` () = let ``DenseMatrix.init_row`` () =
DenseMatrix.initRow 100 100 (fun i -> (DenseVector.init 100 (fun j -> float i * 100.0 + float j))) |> should equal largeM DenseMatrix.initRow 100 100 (fun i -> (DenseVector.init 100 (fun j -> float i * 100.0 + float j))) |> should equal largeM
[<Test>] [<Test>]
let ``DenseMatrix.init_col`` () = let ``DenseMatrix.init_col`` () =
DenseMatrix.initCol 100 100 (fun j -> (DenseVector.init 100 (fun i -> float i * 100.0 + float j))) |> should equal largeM DenseMatrix.initCol 100 100 (fun j -> (DenseVector.init 100 (fun i -> float i * 100.0 + float j))) |> should equal largeM

30
src/FSharpUnitTests/DenseVectorTests.fs

@ -13,23 +13,23 @@ module DenseVectorTests =
/// A large vector with increasingly large entries /// A large vector with increasingly large entries
let largev = new DenseVector( Array.init 100 (fun i -> float i / 100.0) ) let largev = new DenseVector( Array.init 100 (fun i -> float i / 100.0) )
[<Test>] [<Test>]
let ``DenseVector.init`` () = let ``DenseVector.init`` () =
DenseVector.init 100 (fun i -> float i / 100.0) |> should equal largev DenseVector.init 100 (fun i -> float i / 100.0) |> should equal largev
[<Test>] [<Test>]
let ``DenseVector.ofList`` () = let ``DenseVector.ofList`` () =
DenseVector.ofList [ for i in 0 .. 99 -> float i / 100.0 ] |> should equal largev DenseVector.ofList [ for i in 0 .. 99 -> float i / 100.0 ] |> should equal largev
[<Test>] [<Test>]
let ``DenseVector.ofSeq`` () = let ``DenseVector.ofSeq`` () =
DenseVector.ofSeq (seq { for i in 0 .. 99 -> float i / 100.0 }) |> should equal largev DenseVector.ofSeq (seq { for i in 0 .. 99 -> float i / 100.0 }) |> should equal largev
[<Test>] [<Test>]
let ``DenseVector.rangef`` () = let ``DenseVector.rangef`` () =
DenseVector.rangef 0.0 0.01 0.99 |> should equal (new DenseVector( [| for i in 0 .. 99 -> 0.01 * float i |] ) ) DenseVector.rangef 0.0 0.01 0.99 |> should equal (new DenseVector( [| for i in 0 .. 99 -> 0.01 * float i |] ) )
[<Test>] [<Test>]
let ``DenseVector.range`` () = let ``DenseVector.range`` () =
DenseVector.range 0 99 |> should equal (new DenseVector( [| for i in 0 .. 99 -> float i |] ) ) DenseVector.range 0 99 |> should equal (new DenseVector( [| for i in 0 .. 99 -> float i |] ) )

2
src/FSharpUnitTests/FsUnit.fs

@ -9,7 +9,7 @@ let should (f : 'a -> #Constraint) x (y : obj) =
| :? (unit -> unit) -> box (TestDelegate(y :?> unit -> unit)) | :? (unit -> unit) -> box (TestDelegate(y :?> unit -> unit))
| _ -> y | _ -> y
Assert.That(y, c) Assert.That(y, c)
let equal x = EqualConstraint(x) let equal x = EqualConstraint(x)
let equalWithin tolerance x = equal(x).Within tolerance let equalWithin tolerance x = equal(x).Within tolerance

128
src/FSharpUnitTests/MatrixTests.fs

@ -14,99 +14,99 @@ module MatrixTests =
/// A large vector with increasingly large entries /// A large vector with increasingly large entries
let largeM = new DenseMatrix( Array2D.init 100 100 (fun i j -> float i * 100.0 + float j) ) let largeM = new DenseMatrix( Array2D.init 100 100 (fun i j -> float i * 100.0 + float j) )
[<Test>] [<Test>]
let ``Matrix.fold`` () = let ``Matrix.fold`` () =
Matrix.fold (fun a b -> a - b) 0.0 smallM |> should equal -1.2 Matrix.fold (fun a b -> a - b) 0.0 smallM |> should equal -1.2
[<Test>] [<Test>]
let ``Matrix.foldBack`` () = let ``Matrix.foldBack`` () =
Matrix.foldBack (fun a b -> a - b) 0.0 smallM |> should equal 0.0 Matrix.foldBack (fun a b -> a - b) 0.0 smallM |> should equal 0.0
[<Test>] [<Test>]
let ``Matrix.foldBackSummation`` () = let ``Matrix.foldBackSummation`` () =
Matrix.foldBack( fun a b -> a + b) 0.0 failingFoldBackM |> should equal 6.0 Matrix.foldBack( fun a b -> a + b) 0.0 failingFoldBackM |> should equal 6.0
[<Test>] [<Test>]
let ``Matrix.foldi`` () = let ``Matrix.foldi`` () =
Matrix.foldi (fun i j acc x -> acc + x + float (i+j)) 0.0 smallM |> should equal 5.2 Matrix.foldi (fun i j acc x -> acc + x + float (i+j)) 0.0 smallM |> should equal 5.2
[<Test>] [<Test>]
let ``Matrix.toArray2`` () = let ``Matrix.toArray2`` () =
Matrix.toArray2 smallM |> should array2_equal (Array2D.create 2 2 0.3) Matrix.toArray2 smallM |> should array2_equal (Array2D.create 2 2 0.3)
[<Test>] [<Test>]
let ``Matrix.forall`` () = let ``Matrix.forall`` () =
Matrix.forall (fun x -> x = 0.3) smallM |> should equal true Matrix.forall (fun x -> x = 0.3) smallM |> should equal true
[<Test>] [<Test>]
let ``Matrix.exists`` () = let ``Matrix.exists`` () =
Matrix.exists (fun x -> x = 0.5) smallM |> should equal false Matrix.exists (fun x -> x = 0.5) smallM |> should equal false
[<Test>] [<Test>]
let ``Matrix.foralli`` () = let ``Matrix.foralli`` () =
Matrix.foralli (fun i j x -> x = float i * 100.0 + float j) largeM |> should equal true Matrix.foralli (fun i j x -> x = float i * 100.0 + float j) largeM |> should equal true
[<Test>] [<Test>]
let ``Matrix.existsi`` () = let ``Matrix.existsi`` () =
Matrix.existsi (fun i j x -> x = float i * 100.0 + float j) largeM |> should equal true Matrix.existsi (fun i j x -> x = float i * 100.0 + float j) largeM |> should equal true
[<Test>] [<Test>]
let ``Matrix.map`` () = let ``Matrix.map`` () =
Matrix.map (fun x -> 2.0 * x) smallM |> should equal (2.0 * smallM) Matrix.map (fun x -> 2.0 * x) smallM |> should equal (2.0 * smallM)
[<Test>] [<Test>]
let ``Matrix.mapi`` () = let ``Matrix.mapi`` () =
Matrix.mapi (fun i j x -> float i * 100.0 + float j + x) largeM |> should equal (2.0 * largeM) Matrix.mapi (fun i j x -> float i * 100.0 + float j + x) largeM |> should equal (2.0 * largeM)
[<Test>] [<Test>]
let ``Matrix.mapCols`` () = let ``Matrix.mapCols`` () =
Matrix.mapCols (fun j col -> col.Add(float j)) smallM |> should (approximately_matrix_equal 14) (matrix [[0.3;1.3];[0.3;1.3]]) Matrix.mapCols (fun j col -> col.Add(float j)) smallM |> should (approximately_matrix_equal 14) (matrix [[0.3;1.3];[0.3;1.3]])
[<Test>] [<Test>]
let ``Matrix.mapRows`` () = let ``Matrix.mapRows`` () =
Matrix.mapRows (fun i row -> row.Add(float i)) smallM |> should (approximately_matrix_equal 14) (matrix [[0.3;0.3];[1.3;1.3]]) Matrix.mapRows (fun i row -> row.Add(float i)) smallM |> should (approximately_matrix_equal 14) (matrix [[0.3;0.3];[1.3;1.3]])
[<Test>] [<Test>]
let ``Matrix.inplaceAssign`` () = let ``Matrix.inplaceAssign`` () =
let N = smallM.Clone() let N = smallM.Clone()
Matrix.inplaceAssign (fun i j -> 0.0) N Matrix.inplaceAssign (fun i j -> 0.0) N
N |> should equal (0.0 * smallM) N |> should equal (0.0 * smallM)
[<Test>] [<Test>]
let ``Matrix.inplaceMapi`` () = let ``Matrix.inplaceMapi`` () =
let N = largeM.Clone() let N = largeM.Clone()
Matrix.inplaceMapi (fun i j x -> 2.0 * (float i * 100.0 + float j) + x) N Matrix.inplaceMapi (fun i j x -> 2.0 * (float i * 100.0 + float j) + x) N
N |> should equal (3.0 * largeM) N |> should equal (3.0 * largeM)
[<Test>] [<Test>]
let ``Matrix.nonZeroEntries`` () = let ``Matrix.nonZeroEntries`` () =
Seq.length (Matrix.nonZeroEntries smallM) |> should equal 4 Seq.length (Matrix.nonZeroEntries smallM) |> should equal 4
[<Test>] [<Test>]
let ``Matrix.sum`` () = let ``Matrix.sum`` () =
Matrix.sum smallM |> should equal 1.2 Matrix.sum smallM |> should equal 1.2
[<Test>] [<Test>]
let ``Matrix.sumColsBy`` () = let ``Matrix.sumColsBy`` () =
Matrix.sumColsBy (fun j col -> col.[0] * col.[1]) (matrix [[1.0; 2.0]; [3.0; 4.0]]) |> should equal 11.0 Matrix.sumColsBy (fun j col -> col.[0] * col.[1]) (matrix [[1.0; 2.0]; [3.0; 4.0]]) |> should equal 11.0
[<Test>] [<Test>]
let ``Matrix.sumRowsBy`` () = let ``Matrix.sumRowsBy`` () =
Matrix.sumRowsBy (fun i row -> row.[0] * row.[1]) (matrix [[1.0; 2.0]; [3.0; 4.0]]) |> should equal 14.0 Matrix.sumRowsBy (fun i row -> row.[0] * row.[1]) (matrix [[1.0; 2.0]; [3.0; 4.0]]) |> should equal 14.0
[<Test>] [<Test>]
let ``Matrix.foldCol`` () = let ``Matrix.foldCol`` () =
Matrix.foldCol (+) 0.0 largeM 0 |> should equal 495000.0 Matrix.foldCol (+) 0.0 largeM 0 |> should equal 495000.0
[<Test>] [<Test>]
let ``Matrix.foldRow`` () = let ``Matrix.foldRow`` () =
Matrix.foldRow (+) 0.0 largeM 0 |> should equal 4950.0 Matrix.foldRow (+) 0.0 largeM 0 |> should equal 4950.0
[<Test>] [<Test>]
let ``Matrix.foldByCol`` () = let ``Matrix.foldByCol`` () =
Matrix.foldByCol (+) 0.0 smallM |> should equal (DenseVector.ofList [0.6;0.6] :> Vector<float>) Matrix.foldByCol (+) 0.0 smallM |> should equal (DenseVector.ofList [0.6;0.6] :> Vector<float>)
[<Test>] [<Test>]
let ``Matrix.foldByRow`` () = let ``Matrix.foldByRow`` () =
Matrix.foldByRow (+) 0.0 smallM |> should equal (DenseVector.ofList [0.6;0.6] :> Vector<float>) Matrix.foldByRow (+) 0.0 smallM |> should equal (DenseVector.ofList [0.6;0.6] :> Vector<float>)

32
src/FSharpUnitTests/RandomVariableTests.fs

@ -17,9 +17,9 @@ let sumOfTwoFairDices = randomVariable {
[<Test>] [<Test>]
let ``When creating two fair dices, then P(Sum of 2 dices = 7) should be 1/6``() = let ``When creating two fair dices, then P(Sum of 2 dices = 7) should be 1/6``() =
sumOfTwoFairDices sumOfTwoFairDices
|> RandomVariable.filter ((=) 7) |> RandomVariable.filter ((=) 7)
|> RandomVariable.probability |> RandomVariable.probability
|> should equal (1N/6N) |> should equal (1N/6N)
let fairCoinAndDice = randomVariable { let fairCoinAndDice = randomVariable {
@ -29,23 +29,23 @@ let fairCoinAndDice = randomVariable {
[<Test>] [<Test>]
let ``When creating a fair coin and a fair dice, then P(Heads) should be 1/2``() = let ``When creating a fair coin and a fair dice, then P(Heads) should be 1/2``() =
fairCoinAndDice fairCoinAndDice
|> RandomVariable.filter (fun (_,c) -> c = Heads) |> RandomVariable.filter (fun (_,c) -> c = Heads)
|> RandomVariable.probability |> RandomVariable.probability
|> should equal (1N/2N) |> should equal (1N/2N)
[<Test>] [<Test>]
let ``When creating a fair coin and a fair dice, then P(Heads and dice > 3) should be 1/4``() = let ``When creating a fair coin and a fair dice, then P(Heads and dice > 3) should be 1/4``() =
fairCoinAndDice fairCoinAndDice
|> RandomVariable.filter (fun (d,c) -> c = Heads && d > 3) |> RandomVariable.filter (fun (d,c) -> c = Heads && d > 3)
|> RandomVariable.probability |> RandomVariable.probability
|> should equal (1N/4N) |> should equal (1N/4N)
// MontyHall Problem // MontyHall Problem
// See Martin Erwig and Steve Kollmansberger's paper // See Martin Erwig and Steve Kollmansberger's paper
// "Functional Pearls: Probabilistic functional programming in Haskell" // "Functional Pearls: Probabilistic functional programming in Haskell"
type Outcome = type Outcome =
| Car | Car
| Goat | Goat
@ -53,18 +53,18 @@ let firstChoice = RandomVariable.toUniformDistribution [Car; Goat; Goat]
let switch firstCoice = let switch firstCoice =
match firstCoice with match firstCoice with
| Car -> | Car ->
// If you had the car and you switch ==> you lose since there are only goats left // If you had the car and you switch ==> you lose since there are only goats left
RandomVariable.certainly Goat RandomVariable.certainly Goat
| Goat -> | Goat ->
// If you had the goat, the host has to take out another goat ==> you win // If you had the goat, the host has to take out another goat ==> you win
RandomVariable.certainly Car RandomVariable.certainly Car
[<Test>] [<Test>]
let ``When making the first choice in a MontyHall situation, the chances to win should be 1/3``() = let ``When making the first choice in a MontyHall situation, the chances to win should be 1/3``() =
firstChoice firstChoice
|> RandomVariable.filter ((=) Car) |> RandomVariable.filter ((=) Car)
|> RandomVariable.probability |> RandomVariable.probability
|> should equal (1N/3N) |> should equal (1N/3N)
let montyHallWithSwitch = randomVariable { let montyHallWithSwitch = randomVariable {
@ -75,5 +75,5 @@ let montyHallWithSwitch = randomVariable {
let ``When switching in a MontyHall situation, the chances to win should be 2/3``() = let ``When switching in a MontyHall situation, the chances to win should be 2/3``() =
montyHallWithSwitch montyHallWithSwitch
|> RandomVariable.filter ((=) Car) |> RandomVariable.filter ((=) Car)
|> RandomVariable.probability |> RandomVariable.probability
|> should equal (2N/3N) |> should equal (2N/3N)

10
src/FSharpUnitTests/SparseMatrixTests.fs

@ -3,23 +3,23 @@
open NUnit.Framework open NUnit.Framework
open FsUnit open FsUnit
open MathNet.Numerics.LinearAlgebra.Generic open MathNet.Numerics.LinearAlgebra.Generic
open MathNet.Numerics.LinearAlgebra.Double open MathNet.Numerics.LinearAlgebra.Double
/// Unit tests for the sparse matrix type. /// Unit tests for the sparse matrix type.
module SparseMatrixTests = module SparseMatrixTests =
/// A small uniform vector. /// A small uniform vector.
let smallM = DenseMatrix.init 4 4 (fun i j -> if i = 1 && j = 2 then 1.0 else 0.0) :> Matrix<float> let smallM = DenseMatrix.init 4 4 (fun i j -> if i = 1 && j = 2 then 1.0 else 0.0) :> Matrix<float>
[<Test>] [<Test>]
let ``SparseMatrix.ofList`` () = let ``SparseMatrix.ofList`` () =
(SparseMatrix.ofList 4 4 [(1,2,1.0)] :> Matrix<float>) |> should equal smallM (SparseMatrix.ofList 4 4 [(1,2,1.0)] :> Matrix<float>) |> should equal smallM
[<Test>] [<Test>]
let ``SparseMatrix.ofSeq`` () = let ``SparseMatrix.ofSeq`` () =
(SparseMatrix.ofSeq 4 4 (Seq.ofList [(1,2,1.0)]) :> Matrix<float>) |> should equal smallM (SparseMatrix.ofSeq 4 4 (Seq.ofList [(1,2,1.0)]) :> Matrix<float>) |> should equal smallM
[<Test>] [<Test>]
let ``SparseMatrix.constDiag`` () = let ``SparseMatrix.constDiag`` () =
SparseMatrix.constDiag 100 2.0 |> should equal (2.0 * (SparseMatrix.Identity 100)) SparseMatrix.constDiag 100 2.0 |> should equal (2.0 * (SparseMatrix.Identity 100))

12
src/FSharpUnitTests/SparseVectorTests.fs

@ -10,12 +10,12 @@ module SparseVectorTests =
/// A small uniform vector. /// A small uniform vector.
let smallv = new DenseVector( [|0.0;0.3;0.0;0.0;0.0|] ) :> Vector<float> let smallv = new DenseVector( [|0.0;0.3;0.0;0.0;0.0|] ) :> Vector<float>
[<Test>] [<Test>]
let ``SparseVector.ofList`` () = let ``SparseVector.ofList`` () =
(SparseVector.ofList 5 [ (1,0.3) ] :> Vector<float>) |> should equal smallv (SparseVector.ofList 5 [ (1,0.3) ] :> Vector<float>) |> should equal smallv
[<Test>] [<Test>]
let ``SparseVector.ofSeq`` () = let ``SparseVector.ofSeq`` () =
(SparseVector.ofSeq 5 (List.toSeq [ (1,0.3) ]) :> Vector<float>) |> should equal smallv (SparseVector.ofSeq 5 (List.toSeq [ (1,0.3) ]) :> Vector<float>) |> should equal smallv

56
src/FSharpUnitTests/Utilities.fs

@ -1,4 +1,4 @@
// First version copied from the F# Power Pack // First version copied from the F# Power Pack
// https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack.Unittests/Utilities.fs // https://raw.github.com/fsharp/powerpack/master/src/FSharp.PowerPack.Unittests/Utilities.fs
namespace MathNet.Numerics.Tests namespace MathNet.Numerics.Tests
@ -7,9 +7,9 @@ open System
open System.Collections.Generic open System.Collections.Generic
[<AutoOpen>] [<AutoOpen>]
module Utilities = module Utilities =
let test msg b = Assert.IsTrue(b, "MiniTest '" + msg + "'") let test msg b = Assert.IsTrue(b, "MiniTest '" + msg + "'")
let logMessage msg = let logMessage msg =
System.Console.WriteLine("LOG:" + msg) System.Console.WriteLine("LOG:" + msg)
// System.Diagnostics.Trace.WriteLine("LOG:" + msg) // System.Diagnostics.Trace.WriteLine("LOG:" + msg)
let check msg v1 v2 = test msg (v1 = v2) let check msg v1 v2 = test msg (v1 = v2)
@ -18,85 +18,85 @@ module Utilities =
let throws f = try f() |> ignore; false with e -> true let throws f = try f() |> ignore; false with e -> true
let countEnumeratorsAndCheckedDisposedAtMostOnceAtEnd (seq: seq<'a>) = let countEnumeratorsAndCheckedDisposedAtMostOnceAtEnd (seq: seq<'a>) =
let enumerator() = let enumerator() =
numActiveEnumerators := !numActiveEnumerators + 1; numActiveEnumerators := !numActiveEnumerators + 1;
let disposed = ref false in let disposed = ref false in
let endReached = ref false in let endReached = ref false in
let ie = seq.GetEnumerator() in let ie = seq.GetEnumerator() in
{ new System.Collections.Generic.IEnumerator<'a> with { new System.Collections.Generic.IEnumerator<'a> with
member x.Current = member x.Current =
test "rvlrve0" (not !endReached); test "rvlrve0" (not !endReached);
test "rvlrve1" (not !disposed); test "rvlrve1" (not !disposed);
ie.Current ie.Current
member x.Dispose() = member x.Dispose() =
test "rvlrve2" !endReached; test "rvlrve2" !endReached;
test "rvlrve4" (not !disposed); test "rvlrve4" (not !disposed);
numActiveEnumerators := !numActiveEnumerators - 1; numActiveEnumerators := !numActiveEnumerators - 1;
disposed := true; disposed := true;
ie.Dispose() ie.Dispose()
interface System.Collections.IEnumerator with interface System.Collections.IEnumerator with
member x.MoveNext() = member x.MoveNext() =
test "rvlrve0" (not !endReached); test "rvlrve0" (not !endReached);
test "rvlrve3" (not !disposed); test "rvlrve3" (not !disposed);
endReached := not (ie.MoveNext()); endReached := not (ie.MoveNext());
not !endReached not !endReached
member x.Current = member x.Current =
test "qrvlrve0" (not !endReached); test "qrvlrve0" (not !endReached);
test "qrvlrve1" (not !disposed); test "qrvlrve1" (not !disposed);
box ie.Current box ie.Current
member x.Reset() = member x.Reset() =
ie.Reset() ie.Reset()
} in } in
{ new seq<'a> with { new seq<'a> with
member x.GetEnumerator() = enumerator() member x.GetEnumerator() = enumerator()
interface System.Collections.IEnumerable with interface System.Collections.IEnumerable with
member x.GetEnumerator() = (enumerator() :> _) } member x.GetEnumerator() = (enumerator() :> _) }
let countEnumeratorsAndCheckedDisposedAtMostOnce (seq: seq<'a>) = let countEnumeratorsAndCheckedDisposedAtMostOnce (seq: seq<'a>) =
let enumerator() = let enumerator() =
let disposed = ref false in let disposed = ref false in
let endReached = ref false in let endReached = ref false in
let ie = seq.GetEnumerator() in let ie = seq.GetEnumerator() in
numActiveEnumerators := !numActiveEnumerators + 1; numActiveEnumerators := !numActiveEnumerators + 1;
{ new System.Collections.Generic.IEnumerator<'a> with { new System.Collections.Generic.IEnumerator<'a> with
member x.Current = member x.Current =
test "qrvlrve0" (not !endReached); test "qrvlrve0" (not !endReached);
test "qrvlrve1" (not !disposed); test "qrvlrve1" (not !disposed);
ie.Current ie.Current
member x.Dispose() = member x.Dispose() =
test "qrvlrve4" (not !disposed); test "qrvlrve4" (not !disposed);
numActiveEnumerators := !numActiveEnumerators - 1; numActiveEnumerators := !numActiveEnumerators - 1;
disposed := true; disposed := true;
ie.Dispose() ie.Dispose()
interface System.Collections.IEnumerator with interface System.Collections.IEnumerator with
member x.MoveNext() = member x.MoveNext() =
test "qrvlrve0" (not !endReached); test "qrvlrve0" (not !endReached);
test "qrvlrve3" (not !disposed); test "qrvlrve3" (not !disposed);
endReached := not (ie.MoveNext()); endReached := not (ie.MoveNext());
not !endReached not !endReached
member x.Current = member x.Current =
test "qrvlrve0" (not !endReached); test "qrvlrve0" (not !endReached);
test "qrvlrve1" (not !disposed); test "qrvlrve1" (not !disposed);
box ie.Current box ie.Current
member x.Reset() = member x.Reset() =
ie.Reset() ie.Reset()
} in } in
{ new seq<'a> with { new seq<'a> with
member x.GetEnumerator() = enumerator() member x.GetEnumerator() = enumerator()
interface System.Collections.IEnumerable with interface System.Collections.IEnumerable with
member x.GetEnumerator() = (enumerator() :> _) } member x.GetEnumerator() = (enumerator() :> _) }
// Verifies two sequences are equal (same length, equiv elements) // Verifies two sequences are equal (same length, equiv elements)
let verifySeqsEqual seq1 seq2 = let verifySeqsEqual seq1 seq2 =
if Seq.length seq1 <> Seq.length seq2 then Assert.Fail() if Seq.length seq1 <> Seq.length seq2 then Assert.Fail()
let zippedElements = Seq.zip seq1 seq2 let zippedElements = Seq.zip seq1 seq2
if zippedElements |> Seq.forall (fun (a, b) -> a = b) if zippedElements |> Seq.forall (fun (a, b) -> a = b)
then () then ()
else Assert.Fail() else Assert.Fail()
/// Check that the lamda throws an exception of the given type. Otherwise /// Check that the lamda throws an exception of the given type. Otherwise
/// calls Assert.Fail() /// calls Assert.Fail()
let private checkThrowsExn<'a when 'a :> exn> (f : unit -> unit) = let private checkThrowsExn<'a when 'a :> exn> (f : unit -> unit) =

118
src/FSharpUnitTests/VectorTests.fs

@ -13,91 +13,91 @@ module VectorTests =
/// A large vector with increasingly large entries /// A large vector with increasingly large entries
let largev = new DenseVector(Array.init 100 (fun i -> float i / 100.0)) :> Vector<float> let largev = new DenseVector(Array.init 100 (fun i -> float i / 100.0)) :> Vector<float>
[<Test>] [<Test>]
let ``Vector.toArray`` () = let ``Vector.toArray`` () =
Vector.toArray smallv |> should array_equal [|0.3;0.3;0.3;0.3;0.3|] Vector.toArray smallv |> should array_equal [|0.3;0.3;0.3;0.3;0.3|]
[<Test>] [<Test>]
let ``Vector.toList`` () = let ``Vector.toList`` () =
Vector.toList smallv |> should equal [0.3;0.3;0.3;0.3;0.3] Vector.toList smallv |> should equal [0.3;0.3;0.3;0.3;0.3]
[<Test>] [<Test>]
let ``Vector.mapInPlace`` () = let ``Vector.mapInPlace`` () =
let w = smallv.Clone() let w = smallv.Clone()
Vector.mapInPlace (fun x -> 2.0 * x) w Vector.mapInPlace (fun x -> 2.0 * x) w
w |> should equal (2.0 * smallv) w |> should equal (2.0 * smallv)
[<Test>] [<Test>]
let ``Vector.mapiInPlace`` () = let ``Vector.mapiInPlace`` () =
let w = largev.Clone() let w = largev.Clone()
Vector.mapiInPlace (fun i x -> float i / 100.0) w Vector.mapiInPlace (fun i x -> float i / 100.0) w
w |> should equal (largev) w |> should equal (largev)
[<Test>] [<Test>]
let ``Vector.addInPlace`` () = let ``Vector.addInPlace`` () =
let w = largev.Clone() let w = largev.Clone()
Vector.addInPlace w largev Vector.addInPlace w largev
w |> should equal (2.0 * largev) w |> should equal (2.0 * largev)
[<Test>] [<Test>]
let ``Vector.subInPlace`` () = let ``Vector.subInPlace`` () =
let w = largev.Clone() let w = largev.Clone()
Vector.subInPlace w largev Vector.subInPlace w largev
w |> should equal (0.0 * largev) w |> should equal (0.0 * largev)
[<Test>] [<Test>]
let ``Vector.map`` () = let ``Vector.map`` () =
Vector.map (fun x -> 2.0 * x) largev |> should equal (2.0 * largev) Vector.map (fun x -> 2.0 * x) largev |> should equal (2.0 * largev)
[<Test>] [<Test>]
let ``Vector.mapi`` () = let ``Vector.mapi`` () =
Vector.mapi (fun i x -> float i / 100.0) largev |> should equal largev Vector.mapi (fun i x -> float i / 100.0) largev |> should equal largev
[<Test>] [<Test>]
let ``Vector.fold`` () = let ``Vector.fold`` () =
Vector.fold (fun a b -> a - b) 0.0 smallv |> should equal -1.5 Vector.fold (fun a b -> a - b) 0.0 smallv |> should equal -1.5
[<Test>] [<Test>]
let ``Vector.foldBack`` () = let ``Vector.foldBack`` () =
Vector.foldBack (fun a b -> a - b) 0.0 smallv |> should equal 0.0 Vector.foldBack (fun a b -> a - b) 0.0 smallv |> should equal 0.0
[<Test>] [<Test>]
let ``Vector.foldi`` () = let ``Vector.foldi`` () =
Vector.foldi (fun i a b -> a + b) 0.0 smallv |> should equal 1.5 Vector.foldi (fun i a b -> a + b) 0.0 smallv |> should equal 1.5
[<Test>] [<Test>]
let ``Vector.forall`` () = let ``Vector.forall`` () =
Vector.forall (fun x -> x = 0.3) smallv |> should equal true Vector.forall (fun x -> x = 0.3) smallv |> should equal true
[<Test>] [<Test>]
let ``Vector.exists`` () = let ``Vector.exists`` () =
Vector.exists (fun x -> x = 0.3) smallv |> should equal true Vector.exists (fun x -> x = 0.3) smallv |> should equal true
[<Test>] [<Test>]
let ``Vector.foralli`` () = let ``Vector.foralli`` () =
Vector.foralli (fun i x -> x = 0.3 && i < 5) smallv |> should equal true Vector.foralli (fun i x -> x = 0.3 && i < 5) smallv |> should equal true
[<Test>] [<Test>]
let ``Vector.existsi`` () = let ``Vector.existsi`` () =
Vector.existsi (fun i x -> x = 0.3 && i = 2) smallv |> should equal true Vector.existsi (fun i x -> x = 0.3 && i = 2) smallv |> should equal true
[<Test>] [<Test>]
let ``Vector.scan`` () = let ``Vector.scan`` () =
Vector.scan (fun acc x -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|0.3;0.6;0.9;1.2;1.5|] ) :> Vector<float>) Vector.scan (fun acc x -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|0.3;0.6;0.9;1.2;1.5|] ) :> Vector<float>)
[<Test>] [<Test>]
let ``Vector.scanBack`` () = let ``Vector.scanBack`` () =
Vector.scanBack (fun x acc -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|1.5;1.2;0.9;0.6;0.3|] ) :> Vector<float>) Vector.scanBack (fun x acc -> acc + x) smallv |> should (approximately_vector_equal 14) (new DenseVector( [|1.5;1.2;0.9;0.6;0.3|] ) :> Vector<float>)
[<Test>] [<Test>]
let ``Vector.reduce`` () = let ``Vector.reduce`` () =
Vector.reduce (fun acc x -> acc ** x) smallv |> should (approximately_equal 14) 0.990295218585507 Vector.reduce (fun acc x -> acc ** x) smallv |> should (approximately_equal 14) 0.990295218585507
[<Test>] [<Test>]
let ``Vector.reduceBack`` () = let ``Vector.reduceBack`` () =
Vector.reduceBack (fun x acc -> x ** acc) smallv |> should (approximately_equal 14) 0.488911287726319 Vector.reduceBack (fun x acc -> x ** acc) smallv |> should (approximately_equal 14) 0.488911287726319
[<Test>] [<Test>]
let ``Vector.insert`` () = let ``Vector.insert`` () =
Vector.insert 2 0.5 smallv |> should (approximately_vector_equal 14) (new DenseVector ( [|0.3;0.3;0.5;0.3;0.3;0.3|] ) :> Vector<float>) Vector.insert 2 0.5 smallv |> should (approximately_vector_equal 14) (new DenseVector ( [|0.3;0.3;0.5;0.3;0.3;0.3|] ) :> Vector<float>)

Loading…
Cancel
Save