brick / math

Arbitrary-precision arithmetic library for PHP
MIT License
1.78k stars 75 forks source link

Number Calculation interface #42

Closed miloshavlicek closed 4 years ago

miloshavlicek commented 4 years ago

Hi, it would be useful to have a Number Calculation interface that will contain methods like plus($that), minus($that), multipliedBy($that) etc...

At this time, BigNumber does not contain these methods and it's ok, however, an interface would be fine.

We can use simple generics notation for that: https://phpstan.org/blog/generics-in-php-using-phpdocs https://psalm.dev/docs/annotating_code/templated_annotations/

BenMorel commented 4 years ago

Hi, what’s the use case for this?

It’s not possible to do this for every method anyway, in particular dividedBy() has different signatures for every class!

BenMorel commented 4 years ago

Closing due to lack of feedback. Please comment if you wish to reopen!

aldenw commented 3 years ago

Here is an example of what I think the use case for this would be. This is what I'm currently doing with a method to add any of the 3 current Big types. Doing the same with subtract, etc.

    /**
     * @param BigInteger|BigRational|BigDecimal $leftOperand
     * @param BigInteger|BigRational|BigDecimal $rightOperand
     *
     * @noinspection PhpDocSignatureInspection
     */
    public static function add(BigNumber $leftOperand, BigNumber $rightOperand): BigNumber
    {
        return $leftOperand->plus($rightOperand);
    }

An interface would make this safe from potential future Big types that may not implement plus, or implement it with a different signature. Also provide better ide support. Currently we have to force the ide to ignore.

It’s not possible to do this for every method anyway, in particular dividedBy()

Definitely true, but I think that doesn't reduce the value of an interface for those methods for which it is possible.