StochasticRoundingStrategy Class
Definition
- Assembly
- Bodu.Financial.dll
- Package
- Bodu.Financial 1.0.0
An IRoundingStrategy that rounds a value up or down probabilistically, with the probability of rounding up equal to the fractional part discarded at the target scale. Over many roundings the expected value equals the raw amount, so the convention is statistically unbiased and does not accumulate the directional drift that a fixed midpoint rule can introduce across a long series of operations.
public sealed class StochasticRoundingStrategy : IRoundingStrategy
- Inheritance
-
StochasticRoundingStrategy
- Implements
- Inherited Members
- Extension Methods
Remarks
For a value whose magnitude beyond scale digits has fractional part f (in the half-open interval
[0, 1)), this strategy rounds up with probability f and down with probability 1 - f. A value
already exact at the target scale is returned unchanged. The rule is applied on the number line (toward positive
infinity for "up"), so negative amounts are unbiased in the same way as positive amounts.
Randomness is drawn from an injected sampler returning a value in [0, 1); the parameterless constructor uses
Shared. Because the result depends on the sampler, this strategy is inherently
non-deterministic and two roundings of the same input may differ - supply a fixed-sequence sampler to make a test
deterministic. Unlike MidpointRoundingStrategy, this convention cannot be expressed as a
MidpointRounding mode, which is why it is a distinct implementation of the
IRoundingStrategy seam rather than another mode of the midpoint strategy.
// Unbiased rounding for a stochastic allocation policy.
var context = new MonetaryContext { Rounding = StochasticRoundingStrategy.Shared };
// Deterministic in a test: a sampler that always draws 0 rounds every non-exact value up.
var up = new StochasticRoundingStrategy(() => 0.0);
decimal r = up.Round(1.001m, 2); // 1.01
Constructors
StochasticRoundingStrategy()
Initializes a new instance of the StochasticRoundingStrategy class backed by Shared.
public StochasticRoundingStrategy()
StochasticRoundingStrategy(Func<double>)
Initializes a new instance of the StochasticRoundingStrategy class backed by the supplied sampler.
public StochasticRoundingStrategy(Func<double> sampler)
Parameters
samplerFunc<double>A function returning a value in the half-open interval
[0, 1)for each rounding.
Exceptions
- ArgumentNullException
Thrown when
sampleris null.
Fields
Shared
The shared strategy backed by Shared, safe for concurrent use.
public static readonly StochasticRoundingStrategy Shared
Field Value
Methods
Round(decimal, int)
Rounds value to scale fractional digits.
public decimal Round(decimal value, int scale)
Parameters
Returns
- decimal
The rounded amount.
Exceptions
- ArgumentOutOfRangeException
scaleis negative or exceeds 28.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |