Kevin,
If all that you ask of this type is that it does arithmetic, clamps any
negative values to zero, and clamps any values greater than one to one,
that is easy enough. Just note that arithmetic with probabilities usually
is more subtle than that.
import Base: +,-,*,/
immutable Probability <: Real
val::Float64
Probability(x::Float64) = min(1.0, max(0.0, x))
end
(+){T<:Probability}(a::T, b::T) = Probability( a.val + b.val )
(-){T<:Probability}(a::T, b::T) = Probability( a.val - b.val )
(*){T<:Probability}(a::T, b::T) = Probability( a.val * b.val )
(/){T<:Probability}(a::T, b::T) = Probability( a.val / b.val )
You need conversion and promotion if you want to mix Float64 values and
Probability values: 2.0 * Probability(0.25) == Probability(0.5).
On Sunday, February 28, 2016 at 10:33:07 AM UTC-5, Kevin Kunzmann wrote:
Hey,
I have a (probably) very simple question. I would like to define
'Probability' as a new subtype of 'Real', only with the additional
restriction that the value must be between 0 and 1. How would I achieve
that 'Julia-style'? This should be possible without having to rewrite all
these promotion rules and stuff, is it not?
Best Kevin