Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,24 @@ public struct BetaDistribution: ContinuousDistribution, UnivariateDistribution {
}

public func pdf(x: Double, logarithmic: Bool = false) -> Double {
switch x {
case ...0, 1...:
return logarithmic ? -.infinity : 0

default:
let logBeta = .logGamma(alpha + beta) - .logGamma(alpha) - .logGamma(beta)
let logX = (alpha - 1) * .log(x) + (beta - 1) * .log(1 - x)
return logarithmic ? logBeta + logX : .exp(logBeta + logX)
let logBeta: Double = .logGamma(alpha + beta) - .logGamma(alpha) - .logGamma(beta)

guard x >= 0, x <= 1 else { return logarithmic ? -.infinity : 0 }

if x == 0 {
if alpha < 1 { return logarithmic ? .infinity : .infinity }
if alpha > 1 { return logarithmic ? -.infinity : 0 }
return logarithmic ? logBeta : .exp(logBeta)
}

if x == 1 {
if beta < 1 { return logarithmic ? .infinity : .infinity }
if beta > 1 { return logarithmic ? -.infinity : 0 }
return logarithmic ? logBeta : .exp(logBeta)
}

let logX = (alpha - 1) * .log(x) + (beta - 1) * .log(1 - x)
return logarithmic ? logBeta + logX : .exp(logBeta + logX)
}

public func cdf(x: Double, logarithmic: Bool = false) -> Double {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,16 @@ struct BetaDistributionTests {
(5.0, 2.0, 0.1, 0.0027),
(5.0, 2.0, 0.9, 1.9683),
(5.0, 2.0, 0.4, 0.4608),
// Boundary points: x = 0
(0.5, 0.5, 0.0, Double.infinity), // alpha < 1 → +∞
(0.9, 0.9, 0.0, Double.infinity), // alpha < 1 → +∞
(1.0, 1.0, 0.0, 1.0), // alpha = 1 → 1/B(α,β) = 1
(2.0, 2.0, 0.0, 0.0), // alpha > 1 → 0
// Boundary points: x = 1
(0.5, 0.5, 1.0, Double.infinity), // beta < 1 → +∞
(0.9, 0.9, 1.0, Double.infinity), // beta < 1 → +∞
(1.0, 1.0, 1.0, 1.0), // beta = 1 → 1/B(α,β) = 1
(2.0, 2.0, 1.0, 0.0), // beta > 1 → 0
]
)
func validInputReturnsCorrectPDF(alpha: Double, beta: Double, x: Double, expectedPDF: Double) async throws {
Expand All @@ -162,6 +172,16 @@ struct BetaDistributionTests {
(0.1, 5000.0, -1.0, -Double.infinity),
(0.1, 5000.0, 0.9, -11511.929057),
(0.1, 5000.0, 0.4, -2554.193633),
// Boundary points: x = 0
(0.5, 0.5, 0.0, Double.infinity), // alpha < 1 → +∞
(0.9, 0.9, 0.0, Double.infinity), // alpha < 1 → +∞
(1.0, 1.0, 0.0, 0.0), // alpha = 1 → log(1/B(1,1)) = 0
(2.0, 2.0, 0.0, -Double.infinity), // alpha > 1 → -∞
// Boundary points: x = 1
(0.5, 0.5, 1.0, Double.infinity), // beta < 1 → +∞
(0.9, 0.9, 1.0, Double.infinity), // beta < 1 → +∞
(1.0, 1.0, 1.0, 0.0), // beta = 1 → log(1/B(1,1)) = 0
(2.0, 2.0, 1.0, -Double.infinity), // beta > 1 → -∞
]
)
func validInputReturnsCorrectLogPDF(alpha: Double, beta: Double, x: Double, expectedLogPDF: Double) async throws {
Expand Down
Loading