Reputation: 120711
In the gcc implementation this works trivially; the parameters are only applied as simple multiply and shift of the actual algorithm's output. But I could imagine other algorithms to have problems with a special case like this. Should I better build in an external safe-guard, or is it fine to just give std::normal_distribution
's constructor a 0 as the standard deviation parameter to get a "non-random distribution", i.e. one that always yields the mean value?
(Performance aside)
Upvotes: 2
Views: 1163
Reputation: 531
As the previous writers pointed out, the normal_distribution function's behavior is only defined for stddev>0.
I'd just like to add that this makes a lot of sense mathematically: For the stddev (width) =0 the Gaussian normal distribution becomes the Dirac delta function.
The Dirac delta function is defined to be ==0 everywhere except for x==0, where it is undefined. However, every integral over the delta function that includes x==0 within its integration limits is defined to be 1, while an integral not including x==0 is 0.
This behavior cannot be represented correctly within the definition of float/double numbers, therefore a normal distribution with stddev=0 has to remain undefined.
Upvotes: 2
Reputation: 110108
You can't use a standard deviation of 0. From the standard, section 26.5.8.5.1:
explicit normal_distribution(RealType mean = 0.0, RealType stddev = 1.0);
Requires: 0 < stddev.
Using a value of 0 would result in undefined behavior, so you'll need to special-case that value.
Upvotes: 3
Reputation: 20191
The standard says the following (§26.5.8.4.4):
explicit normal_distribution(RealType mean = 0.0, RealType stddev = 1.0);
Requires: 0 < stddev.
As such a standard derivation of 0
is explicitly forbidden by the standard and therefore not guaranteed to work. Therefore building an external safeguard seems like a good idea
Even if the typical implemention would work on a standard derivation of 0 (not sure if that is the case), I could imagine an implementation which tests for such a case and throws an exception when the standard derivation is zero and throws an exception if it is not (to ensure that the code is portable). As an alternative it is possible that the code will divide by the standard derivation somewhere, which would also be problematic with a derivation of 0
.
Upvotes: 4