Browse Source

Fitting: Tweaks to F# linear combination fitting

v2
Christoph Ruegg 13 years ago
parent
commit
f01a95d23d
  1. 5
      src/FSharp/LeastSquares.fs
  2. 2
      src/FSharpUnitTests/CurveFittingTests.fs

5
src/FSharp/LeastSquares.fs

@ -50,6 +50,7 @@ module Fit =
|> List.map (fun f -> List.init (Array.length x) (fun i -> f x.[i])) |> List.map (fun f -> List.init (Array.length x) (fun i -> f x.[i]))
|> DenseMatrix.ofColumnsList (Array.length x) (List.length functions) |> DenseMatrix.ofColumnsList (Array.length x) (List.length functions)
|> fun m -> m.QR(QRMethod.Thin).Solve(DenseVector(y)).ToArray() |> fun m -> m.QR(QRMethod.Thin).Solve(DenseVector(y)).ToArray()
|> List.ofArray
let linearf functions x y = let linearf functions x y =
let parameters = linear functions x y |> List.ofArray let parts = linear functions x y |> List.zip functions
in fun z -> functions |> List.zip parameters |> List.fold (fun s (p,f) -> s+p*(f z)) 0.0 in fun z -> parts |> List.fold (fun s (f,p) -> s+p*(f z)) 0.0

2
src/FSharpUnitTests/CurveFittingTests.fs

@ -34,7 +34,7 @@ module CurveFittingTests =
// LeastSquares.FitToLinearCombination(x, y, (fun z -> 1.0), (fun z -> Math.Sin(z)), (fun z -> Math.Cos(z))) // LeastSquares.FitToLinearCombination(x, y, (fun z -> 1.0), (fun z -> Math.Sin(z)), (fun z -> Math.Cos(z)))
(x,y) ||> Fit.linear [(fun _ -> 1.0); (Math.Sin); (Math.Cos) ] (x,y) ||> Fit.linear [(fun _ -> 1.0); (Math.Sin); (Math.Cos) ]
|> should (equalWithin 1.0e-4) [| -0.287476; 4.02159; -1.46962 |] |> should (equalWithin 1.0e-4) [ -0.287476; 4.02159; -1.46962 ]
let fres = LeastSquares.FitToLinearCombinationFunc(x, y, (fun z -> 1.0), (fun z -> Math.Sin(z)), (fun z -> Math.Cos(z))) |> tofs let fres = LeastSquares.FitToLinearCombinationFunc(x, y, (fun z -> 1.0), (fun z -> Math.Sin(z)), (fun z -> Math.Cos(z))) |> tofs
in x |> Array.iter (fun x -> fres x |> should (equalWithin 1.0e-4) (4.02159*Math.Sin(x) - 1.46962*Math.Cos(x) - 0.287476)) in x |> Array.iter (fun x -> fres x |> should (equalWithin 1.0e-4) (4.02159*Math.Sin(x) - 1.46962*Math.Cos(x) - 0.287476))

Loading…
Cancel
Save