Skip to content

Commit

Permalink
[FSharp] Add stableSum and stableSumBy
Browse files Browse the repository at this point in the history
  • Loading branch information
hyazinthh committed Feb 12, 2025
1 parent 7d99af5 commit 8f90ff7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
- [FSharp] Added stableSum and stableSumBy for List, Array, and Seq

### 5.3.7
- Marked quaternion to matrix conversion obsolete as it is misleading
- Added conversions between ranges and 2D vectors
Expand Down
30 changes: 30 additions & 0 deletions src/Aardvark.Base.FSharp/Utilities/Interop/FSLibExtensions.fs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,16 @@ module Prelude =

res

/// Computes the sum of the given sequence using the Kahan summation algorithm.
let inline stableSumBy (projection: 'T -> float) (source: 'T seq) =
let mutable sum = KahanSum.Zero
for x in source do sum <- sum + projection x
sum.Value

/// Computes the sum of the given sequence using the Kahan summation algorithm.
let inline stableSum (source: float seq) =
stableSumBy id source

open System.Collections
open System.Collections.Generic

Expand Down Expand Up @@ -158,6 +168,16 @@ module Prelude =
| xs -> x::separator::xs
)

/// Computes the sum of the given list using the Kahan summation algorithm.
let inline stableSumBy (projection: 'T -> float) (list: 'T list) =
let mutable sum = KahanSum.Zero
for x in list do sum <- sum + projection x
sum.Value

/// Computes the sum of the given list using the Kahan summation algorithm.
let inline stableSum (list: float list) =
stableSumBy id list

module Array =

let inline foldi (folder : int -> 'State -> 'T -> 'State) (state : 'State) (array : 'T[]) =
Expand Down Expand Up @@ -194,6 +214,16 @@ module Prelude =

loop 0

/// Computes the sum of the given array using the Kahan summation algorithm.
let inline stableSumBy (projection: 'T -> float) (array: 'T[]) =
let mutable sum = KahanSum.Zero
for x in array do sum <- sum + projection x
sum.Value

/// Computes the sum of the given array using the Kahan summation algorithm.
let inline stableSum (array: float[]) =
stableSumBy id array

module Disposable =

let empty = { new IDisposable with member x.Dispose() = () }
Expand Down

0 comments on commit 8f90ff7

Please sign in to comment.