From d3c97c25ff1ec2e9e308fac8872ee09e7c903be7 Mon Sep 17 00:00:00 2001 From: Alex Mason Date: Mon, 11 Aug 2025 00:00:29 +1000 Subject: [PATCH 1/2] Make exponentiation significantly faster Tail-recursive variant is much faster --- Statistics/Sample.hs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Statistics/Sample.hs b/Statistics/Sample.hs index f47b9ea..d5450f4 100644 --- a/Statistics/Sample.hs +++ b/Statistics/Sample.hs @@ -1,4 +1,5 @@ {-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE BangPatterns #-} -- | -- Module : Statistics.Sample -- Copyright : (c) 2008 Don Stewart, 2009 Bryan O'Sullivan @@ -453,7 +454,14 @@ pair va vb -- (^) operator from Prelude is just slow. (^) :: Double -> Int -> Double x ^ 1 = x -x ^ n = x * (x ^ (n-1)) +x ^ 2 = x * x +x ^ 3 = x * x * x +x ^ 4 = (x * x) * (x * x) +x ^ 5 = (x * x) * x * (x * x) +-- x ^ n = x * (x ^ (n-1)) +x0 ^ n0 = go (n0-1) x0 where + go 0 !acc = acc + go n acc = go (n-1) (acc*x0) {-# INLINE (^) #-} -- don't support polymorphism, as we can't get unboxed returns if we use it. From 0a34059050a1347acd175ae4d90cdd9db838840f Mon Sep 17 00:00:00 2001 From: Alexey Khudyakov Date: Mon, 1 Sep 2025 14:40:28 +0300 Subject: [PATCH 2/2] Drop manual unrolling We don't get specialization and gains are relatively small. Let go with simpler solution --- Statistics/Sample.hs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Statistics/Sample.hs b/Statistics/Sample.hs index d5450f4..39b1930 100644 --- a/Statistics/Sample.hs +++ b/Statistics/Sample.hs @@ -453,12 +453,6 @@ pair va vb -- (^) operator from Prelude is just slow. (^) :: Double -> Int -> Double -x ^ 1 = x -x ^ 2 = x * x -x ^ 3 = x * x * x -x ^ 4 = (x * x) * (x * x) -x ^ 5 = (x * x) * x * (x * x) --- x ^ n = x * (x ^ (n-1)) x0 ^ n0 = go (n0-1) x0 where go 0 !acc = acc go n acc = go (n-1) (acc*x0)