rfc:stochastic_rounding_mode

PHP RFC: Stochastic Rounding Mode

Introduction

Rounding modes use some rule to determine in which direction a supplied value should be rounded. While all of the rounding modes available in PHP right now are deterministic, there are other ways that rounding can occur.

This RFC proposes adding a stochastic rounding mode that uses a weighted random process to determine the rounding direction.

Proposal

A stochastic rounding mode rounds with a probability that corresponds to the value being rounded. For instance:

$val = round(1.8, 0 \RoundingMode::Stochastic);
 
echo $val; 
// 20% of the time, this will echo "1"
// 80% of the time, this will echo "2"

This mode ensures that if the same value is rounded many times, the average value of the rounded numbers will approach the original number. This is mainly used in linear algebra, particularly machine learning applications.

New Option For \RoundingMode Enum

The new rounding mode will only be available on the \RoundingMode enum.

enum RoundingMode {
    // Existing Modes
    case HalfAwayFromZero;
    case HalfTowardsZero;
    case HalfEven;
    case HalfOdd;
    case TowardsZero;
    case AwayFromZero;
    case NegativeInfinity;
    case PositiveInfinity;
 
    // New Rounding Mode
    case Stochastic;
}

Backward Incompatible Changes

None

Proposed PHP Version(s)

Next PHP 8.x

RFC Impact

To SAPIs

None

To Existing Extensions

None

To Opcache

None

New Constants

Describe any new constants so they can be accurately and comprehensively explained in the PHP documentation.

Unaffected PHP Functionality

The Intl round function will be unaffected, as it does not accept the \RoundingMode enum.

Future Scope

None

Proposed Voting Choices

Add new stochastic rounding mode as described: yes/no. A 2/3 vote is required to pass.

Vote

Vote will start 2024-XX-XX and will end 2024-XX-XX.

Add stochastic rounding mode?
Real name Yes No
Final result: 0 0
This poll has been closed.

Patches and Tests

The patch will be completed by the RFC author after acceptance.

Implementation

References

Rejected Features

None

rfc/stochastic_rounding_mode.txt · Last modified: 2024/07/05 07:36 by jordanrl