2 people like it.

Curve difference by sum-of-squares

An operator to compare two curves by the sum-of-squares-of-differences method.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
let (-~) a1 a2 = 
    let sq x = x * x
    Array.fold2 (fun acc n1 n2 -> acc + sq (n1 - n2) ) 0. a1 a2

// Examples:

let ones = [|1.; 1.; 1.|]
let twos = [|2.; 2.; 2.|]
let oneTwoThree = [|1.; 2.; 3.|]
let oneishTwoishThreeish =  [|1.1; 1.9; 2.99999|]
let big = [|100.; 101.; 100.|]

// Simple comparisons:
let onesVersusOnes = ones -~ ones // 0.0
let onesVersusTwos = ones -~ twos // 1.0
let twosVersusOnes = twos -~ ones // 0.0
let sameish = oneTwoThree -~ oneishTwoishThreeish // 1e-10
let veryDifferent = ones -~ big // 9801.0

// Order a list of arrays based on their similarity to a 'seed' array:
let ordered =
    let seed = twos
    let list = [oneishTwoishThreeish; big; ones; oneTwoThree]
    list
    |> List.sortBy (fun arr -> arr -~ seed)

// [[|1.1; 1.9; 2.99999|]; [|1.0; 2.0; 3.0|]; [|1.0; 1.0; 1.0|]; [|100.0; 101.0; 100.0|]]
val a1 : float []
val a2 : float []
val sq : (float -> float)
val x : float
module Array

from Microsoft.FSharp.Collections
val fold2 : folder:('State -> 'T1 -> 'T2 -> 'State) -> state:'State -> array1:'T1 [] -> array2:'T2 [] -> 'State

Full name: Microsoft.FSharp.Collections.Array.fold2
val acc : float
val n1 : float
val n2 : float
val ones : float []

Full name: Script.ones
val twos : float []

Full name: Script.twos
val oneTwoThree : float []

Full name: Script.oneTwoThree
val oneishTwoishThreeish : float []

Full name: Script.oneishTwoishThreeish
val big : float []

Full name: Script.big
val onesVersusOnes : float

Full name: Script.onesVersusOnes
val onesVersusTwos : float

Full name: Script.onesVersusTwos
val twosVersusOnes : float

Full name: Script.twosVersusOnes
val sameish : float

Full name: Script.sameish
val veryDifferent : float

Full name: Script.veryDifferent
val ordered : float [] list

Full name: Script.ordered
val seed : float []
Multiple items
val list : float [] list

--------------------
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val sortBy : projection:('T -> 'Key) -> list:'T list -> 'T list (requires comparison)

Full name: Microsoft.FSharp.Collections.List.sortBy
val arr : float []
Raw view Test code New version

More information

Link:http://fssnip.net/al
Posted:12 years ago
Author:Kit Eason
Tags: curve operator fold fold2