Skip to content

Commit

Permalink
clamped box-muller values between [-3,3] and re-scale to achieve a no…
Browse files Browse the repository at this point in the history
…rmal [0,1] value range
  • Loading branch information
sss-create committed Jan 16, 2025
1 parent ee1e4e6 commit f9438dc
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
10 changes: 6 additions & 4 deletions src/Sound/Tidal/UI.hs
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,16 @@ d1 $
Implemented with the Box-Muller transform.
* the max ensures we don't calculate log 0
* the rot in u2 ensures we don't just get the same value as u1
* clamp the Box-Muller generated values in a [-3,3] range
-}
normal :: (Floating a, Ord a) => Pattern a
normal = do
u1 <- max 0.0000001 <$> rand
u2 <- rot 1 rand
let r1 = sqrt (-2 * log u1)
u1 <- max 0.001 <$> rand
u2 <- rotL 1 rand
let r1 = sqrt $ - (2 * log u1)
r2 = cos (2 * pi * u2)
pure ((r1 * r2) + 1) / 2
clamp n = max (-3) (min 3 n)
pure $ clamp (r1 * r2 + 3) / 6

{- | Randomly picks an element from the given list.
Expand Down
8 changes: 4 additions & 4 deletions test/Sound/Tidal/UITest.hs
Original file line number Diff line number Diff line change
Expand Up @@ -142,14 +142,14 @@ run =
describe "normal" $ do
it "produces values within [0,1] in a bell curve" $ do
it "at the start of a cycle" $
queryArc normal (Arc 0 0) `shouldBe`
[Event (Context []) Nothing (Arc 0 0) (0.3370977:: Float)]
queryArc normal (Arc 0 0.1) `shouldBe`
[Event (Context []) Nothing (Arc 0 0.1) (0.5 :: Double)]
it "at 1/4 of a cycle" $
queryArc normal (Arc 0.25 0.25) `shouldBe`
[Event (Context []) Nothing (Arc 0.25 0.25) (0.4723987:: Float)]
[Event (Context []) Nothing (Arc 0.25 0.25) (0.47110511611574907 :: Double)]
it "at 3/4 of a cycle" $
queryArc normal (Arc 0.75 0.75) `shouldBe`
[Event (Context []) Nothing (Arc 0.75 0.75) (0.44856572:: Float)]
[Event (Context []) Nothing (Arc 0.75 0.75) (0.5 :: Double)]

describe "range" $ do
describe "scales a pattern to the supplied range" $ do
Expand Down

0 comments on commit f9438dc

Please sign in to comment.