rfc:add_bcdivmod_to_bcmath

PHP RFC: Add bcdivmod to BCMath

Introduction

BCMath has bcdiv() and bcmod(), and the operation must be performed twice to obtain both the quotient and remainder. This is also true for the BcMath\Number class. Due to BCMath's division mechanism, the quotient and remainder can be obtained in one operation, but the current API is not designed that way.

Proposal

This RFC proposes the addition of a new function bcdivmod() that can obtain the quotient and remainder in one operation, and the corresponding method divmod() of the BcMath\Number class.

This is clearly faster than doing the two operations separately.

The signature is:

/**  @return array{string, string} */
function bcdivmod(string $num1, string $num2, ?int $scale = null): array {}
 
/**  @return array{Number, Number} */
public function divmod(Number|string|int $num, ?int $scale = null, int $roundingMode = PHP_ROUND_HALF_UP): array {}

The return value is an array containing values ​​in the order of quotient and remainder. This is something like a tuple. For reference, the equivalent function in the GMP extension returns a similar array.

https://www.php.net/manual/ja/function.gmp-div-qr.php

An example usage is:

[$quot, $rem] = bcdivmod('123', '2');
 
// $quot is '61'
// $rem is '1'
$slicesOfPizza = new BcMath\Number(8);
$mouthsToFeed = new BcMath\Number(3);
[$perMouth, $slicesLeft] = $slicesOfPizza->divmod($mouthsToFeed);
 
// $perMouth->value is '2'
// $slicesLeft->value is '2'

Naming and return values ​​are inspired by Python and Ruby.

Regarding return values, it was proposed in the mailing list discussion to return them as objects that have these as properties instead of an array. However, since BCMath has significantly better performance in PHP8.4, the overhead of creating the object is probably more significant, and I would still suggest returning the value in an array.

There was an idea to return the value by reference, but it was not adopted because current PHP tends to avoid such implementation.

Backward Incompatible Changes

In theory, this makes it impossible to define functions with the same name in userland. However, when I searched on Github Code Search, I couldn't find any code that used the function with the same name.

Proposed PHP Version(s)

next PHP 8.x (8.4)

RFC Impact

To SAPIs

None.

To Existing Extensions

Only BCMath.

To Opcache

None.

New Constants

None.

php.ini Defaults

None.

Open Issues

None.

Unaffected PHP Functionality

Nothing other than BCMath is affected.

Future Scope

None.

Proposed Voting Choices

As per the voting RFC a yes/no vote with a 2/3 majority is needed for this proposal to be accepted.

Patches and Tests

Yet.

Implementation

Yet.

References

Rejected Features

None.

rfc/add_bcdivmod_to_bcmath.txt · Last modified: 2024/06/30 23:41 by saki