Accuracy in Erlang

The following code gives me 5.999999999999998 in the Result, but the correct answer is 6.

Alpha = math:acos((4*4 + 5*5 - 3*3) / (2*4*5)) Area = 1/2 * 4 * 5 * math:sin(Alpha) 

Is it possible to get 6?

+6
source share
2 answers

You have such a common problem that it has its own website, that every programmer should know about floating point arithmetic . The problem is how floating point arithmetic works in almost every processor on the market that supports FP arithmetic; this does not apply to Erlang.

If regular floating point arithmetic does not give you exact accuracy or precision, you can use an arbitrary precision arithmetic library instead of the built-in arithmetic. GMP may be the best known library, but you will have to wrap it in NIF to use it from Erlang.

There is at least one pure-Erlang alternative , but I have no experience with it, so I cannot personally approve of it.

+23
source

The calculation is performed using standard floating point arithmetic on your equipment. Rounding errors sometimes appear.

Do you really need 15 digits of accuracy?

To get a more accurate value, there are several options:

 > round(Area). % Will round to integer 6 

or you can round to some precision

 round(Area * 10000000) / 10000000. 6.0 

If the goal is to print the value, then printing with the default output for floats gives you less accuracy.

 io:format("~f~n", [Area]). 6.000000 ok 

or with a certain accuracy

 io:format("~.14f~n", [Area]). 6.00000000000000 ok 

NTN

+8
source

Source: https://habr.com/ru/post/898676/


All Articles