math
math copied to clipboard
Add some generic number type when you don't know if the result will be `int` or `decimal`
As far as I know, the bc library (and gmp too I think) works on arbitrary precision numbers and doesn't discriminate between int or float/decimal. I am re-writing a TypeScript library to PHP and now need to use some BigNumber's math, but am not sure whether the calculations should be done on Integers or Decimals.
It would be great if there was some generic number type that would automatically convert to BigInt if there's no decimals after the calculation or BigDecimal otherwise.
Hi, this could have been BigNumber, which already knows how to handle comparison between types, and cross-type additions (see BigNumber::sum().
That being said, plus(), minus() etc. are already defined on subclasses, and they return an instance of the subclass. We cannot move the implementation to BigNumber, and make each operation return a potentially different type than the type you call the method on, without drastically changing the behaviour of the library (for the worse, IMO).
So this would need to be a new class indeed. But it comes with its own challenges: only addition / subtraction / multiplication could be implemented on this class, as the signature of dividedBy() in each number class is different:
BigRational::dividedBy()only needs a divisorBigInteger::dividedBy()needs a divisor and a rounding modeBigDecimal::dividedBy()needs a divisor, a scale and a rounding mode
I'm wondering, if you're re-writing a TS library to PHP, are you dealing with number types? Or with arbitrary precision?
In the former case, the equivalent would just be using float in PHP. AFAIK, Both PHP's float and JS' number are IEEE 754 double-precision numbers, so you should observe the same behaviour (and the same gotchas, obviously).
Closing this as not planned for now. Please feel free to comment if you think this should be reopened!