Skip to content

Commit

Permalink
Merge pull request #96 from venpopov/unary-negation
Browse files Browse the repository at this point in the history
Allow unary negation to work with all distributions
  • Loading branch information
mitchelloharawild authored Mar 31, 2024
2 parents d62dae1 + 2b8ae5e commit 5946354
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# distributional (development version)

## Bug fixes

* Fixed error when using '-' as a unary operator on a distribution different from
`dist_normal()` by @venpopov (#95)

# distributional 0.4.0

## Breaking changes
Expand Down
5 changes: 5 additions & 0 deletions R/default.R
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,11 @@ Math.dist_default <- function(x, ...) {
#' @method Ops dist_default
#' @export
Ops.dist_default <- function(e1, e2) {
if(.Generic %in% c("-", "+") && missing(e2)){
e2 <- e1
e1 <- if(.Generic == "+") 1 else -1
.Generic <- "*"
}
is_dist <- c(inherits(e1, "dist_default"), inherits(e2, "dist_default"))
if(any(vapply(list(e1, e2)[is_dist], dim, numeric(1L)) > 1)){
stop("Transformations of multivariate distributions are not yet supported.")
Expand Down
5 changes: 5 additions & 0 deletions R/transformed.R
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ Math.dist_transformed <- function(x, ...) {
#' @method Ops dist_transformed
#' @export
Ops.dist_transformed <- function(e1, e2) {
if(.Generic %in% c("-", "+") && missing(e2)){
e2 <- e1
e1 <- if(.Generic == "+") 1 else -1
.Generic <- "*"
}
is_dist <- c(inherits(e1, "dist_default"), inherits(e2, "dist_default"))
trans <- if(all(is_dist)) {
if(identical(e1$dist, e2$dist)){
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/test-transformations.R
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,14 @@ test_that("inverses are applied automatically", {
expect_equal(density(1/(1/dist_gamma(4, 3)), 0.5), density(dist_gamma(4, 3), 0.5))

})

test_that("unary negation operator works", {
dist <- dist_normal(1,1)
expect_equal(density(-dist, 0.5), density(dist, -0.5))

dist <- dist_wrap('norm', mean = 1)
expect_equal(density(-dist, 0.5), density(dist, -0.5))

dist <- dist_student_t(3, mu = 1)
expect_equal(density(-dist, 0.5), density(dist, -0.5))
})

0 comments on commit 5946354

Please sign in to comment.