mitchelloharawild / distributional

Vectorised distributions for R
https://pkg.mitchelloharawild.com/distributional
GNU General Public License v3.0
94 stars 15 forks source link

Minor fixes to `quantile(<dist_mixture>)` and `cdf(<dist_sample>)` #86

Closed mjskay closed 1 year ago

mjskay commented 1 year ago

Two minor bugfixes for some issues I ran into when trying to improve support for visualizing discrete distributions in {ggdist}:

x <- dist_mixture(dist_degenerate(1), dist_degenerate(2), dist_degenerate(3), weights = c(0.1, 0.2, 0.7))
quantile(x, c(0, 0.1, 0.3, 1))[[1]]
#> [[1]]
#> [1] 1.000000 1.472202 2.236134 3.000000

This should be 1 1 2 3. This PR changes the implementation of quantile.dist_mixture() to use uniroot() instead of optimise(), which seems to fix the problem (at least, to within the default tolerance of .Machine$double.eps^0.25):

quantile(x, c(0, 0.1, 0.3, 1))
#> [[1]]
#> [1] 1.000000 1.000000 2.000034 3.000000
cdf(dist_sample(list(2)), 2)
#> x 
#> 0 

This should be 1. This PR changes the implementation of cdf.dist_sample() accordingly:

cdf(dist_sample(list(2)), 2)
#> x 
#> 1

Tests are included for both fixes. There is also a minor fix to format(<dist_mixture>), though it didn't seem newsworthy to me.

mitchelloharawild commented 1 year ago

Great, thanks!