On Wed, Mar 27, 2024 at 12:08 AM Aleksander Machniak <a...@alec.pl> wrote:
> On 27.03.2024 01:03, Saki Takamachi wrote: > >> $num = new BcNum('1.23', 2); > >> $result = $num + '1.23456'; > >> $result->value; // '2.46456' > >> $result->scale; // ?? > > > > In this case, `$result->scale` will be `'5'`. I added this to the RFC. > > I'm not sure I like this. Maybe we should be more strict here and treat > the $scale in constructor (and later withScale()) as the actual scale > for all operations. > > For addition, it absolutely should expand scale like this, unless the constructor also defines a default rounding type that is used in that situation. All numbers, while arbitrary, will be finite, so addition will always be exact and known based on inputs prior to calculation. Treating scale like this isn't more strict, it's confusing. For instance: ``` $numA = new Number('1.23', 2); $numB = new Number('1.23456', 5); $expandedScale1 = $numA + $numB; // 2.46456 $expandedScale2 = $numB + $numA; // 2.46456 $strictScale1 = $numA + $numB; // 2.46 assuming truncation $strictScale2 = $numB + $numA; // 2.46456 ``` I ran into this same issue with operand ordering when I was writing my operator overload RFC. There are ways you could do the overload implementation that would get around this for object + object operations, but it's also mathematically unsound and probably unexpected for anyone who is going to the trouble of using an arbitrary precision library. Addition and subtraction should automatically use the largest scale from all operands. Division and multiplication should require a specified scale. Because of this, I'm not entirely sure that specifying a scale in the constructor is actually a good thing. It is incredibly easy to create situations, unless the implementation in C is VERY careful, where the operand positions matter beyond the simple calculation. Multiplication is commutative, but division is not. This would almost certainly lead to some very difficult to track down bugs. Putting scale in the constructor is similar to some of the examples of "possible misuse cases of operator overloading" that I had to go over when I was making my RFC. We definitely want to avoid that if possible for the first number/math object that has operator overloads. Jordan