brick / math

Arbitrary-precision arithmetic library for PHP
MIT License
1.83k stars 78 forks source link

Issue with dividedBy and MultipliedBy? #59

Closed satrio1256 closed 3 years ago

satrio1256 commented 3 years ago

Hi! I'm currently trying to convert this following formula to my code

% increase = (total - (total - current)) Γ· total Γ— 100

However it somehow give different result when I wrote dividedBy then multipliedBy and multipliedBy then dividedBy

$tc & $cc is BigDecimal Object
For testing : 
if $tc = 10 and $cc = 1, the result should be 10
if $tc = 10 and $cc = 2, the result should be 20

BigDecimal::of($tc->minus($tc->minus($cc)))->dividedBy($tc, 0, RoundingMode::HALF_UP)->multipliedBy('100') // always return 0 (incorrect result)
BigDecimal::of($tc->minus($tc->minus($cc)))->multipliedBy('100')->dividedBy($tc, 0, RoundingMode::HALF_UP) // correct result returned

I'm not quite sure if this behavior is intended or there is incorrect implementation from my end..

Thank you for creating this amazingly useful library though πŸ˜„

satrio1256 commented 3 years ago

Oh my bad, there is nothing wrong with your library.. The issue is my docker that did not refresh the code and makes it return 0

BenMorel commented 3 years ago

πŸ‘

Be careful with roundings, too, you’re rounding to 0 decimals here!

Maybe you could use BigRationals for calculations, then convert to a BigDecimal on the very last step.

satrio1256 commented 3 years ago

Got it, thanks for the advice πŸ˜„