# [erlang-questions] Any way to correct the round off errors?

Witold Baryluk baryluk@REDACTED
Sun Sep 20 19:20:15 CEST 2009

```Dnia 2009-09-20, nie o godzinie 19:00 +0200, Masklinn pisze:
> On 20 Sep 2009, at 18:12 , Witold Baryluk wrote:
> > Dnia 2009-09-20, nie o godzinie 18:06 +0200, Masklinn pisze:
> >> On 20 Sep 2009, at 17:22 , Witold Baryluk wrote:
> >>> If you want something which calculates correctly in decimal number,
> >>> use
> >>> integers multiplied with some 10^k power. It is called fixed point
> >>> arithmetic.
> >> Or use a decimal floating-point library such as gmp.
> >
> > Sure. But considering that Erlang already have arbitrary precision
> > integers, writing few functions for add/sub/mul/div isn't very hard :)
>
> Arbitrary precision integers are quite different beasts (and easier to
> handle) than arbitrary precision floats.

I was talking about arbitrary precision integer arithmetic (or fixed
point arithmetic).

given the fact that Erlang already have integer arithmetic.

Something like this will suffice:

-module(fpa).

sub({X,F},{Y,F}) -> {X-Y,F}.
neg({X,F}) -> {-X,F}.
mul({X,F},{Y,F}) -> {(X*Y) div F, F}.
div({X,F},{Y,F}) -> {(X*F) div Y, F}.
fpa_to_float({X,F}) -> X / F.
float_to_fpa6(X) -> {trunc(1000000*X), 1000000}.

"Accurate" binary floating point arithmetic is completely different
story, and few order of magnitud harder, and still quite active research
area in numerical analysis.

--
Witold Baryluk
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: To jest cz??? wiadomo?ci podpisana cyfrowo
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090920/093833d8/attachment.bin>
```