tools4j / decimal4j

Java library for fast fixed-point arithmetic based on longs with support for up to 18 decimal places.
decimal4j.org
MIT License
156 stars 17 forks source link

Do I need to use the zero-garbage methods for simple tasks with unscaled longs #12

Closed martin3361 closed 6 years ago

martin3361 commented 6 years ago

hello, basically in cases where I have simple adding/subtracting/comparing of unscaled values, do I need to use the DecimalArithmetic methods and why?

Let's say (player location x is MutableDecimal3f, arith uses 3 fraction digits too): long someValue = arith.subtract(playerModel.getLocation().getX().unscaledValue(), Decimal3f.HALF.unscaledValue()) vs long someValue = playerModel.getLocation().getX().unscaledValue() - Decimal3f.HALF.unscaledValue()

or arith.compare(playerModel.getLocation().getX().unscaledValue(), Decimal3f.HALF.unscaledValue()) > 0 vs playerModel.getLocation().getX().unscaledValue() > Decimal3f.HALF.unscaledValue()

the API way of doing things looks more verbose and I was wondering if there is any particular benefit of it, mostly when no multiplying/division and no rounding and overflow may take place.

Thank you!

terzerm commented 6 years ago

You are right there is no difference between the two if you are not using checked overflow arithmetics. For consistency reasons I personally would always go through Arithmetic because you can then e.g. make it configurable whether overflow checking mode is used or not. Another advantage is that Arithmetic also supports add/subtract operations for values with different scales.

You are mentioning that you are using MutableDecimal in your model. As indicated in the documentation, the result of the subtract method is then the same as the first operand, i.e. you don't need to use the API at all. Instead you can simply do:

playerModel.getLocation().getX().subtract(0.5);

or if you like this better

playerModel.getLocation().getX().subtract(Decimal3f.HALF);

See also examples for MutableDecimal here