[erlang-questions] why do I see a message about area of a square
ok@REDACTED
ok@REDACTED
Tue Jan 27 13:03:31 CET 2015
> As I understand it right. The eror message is on all functions so on the
> square, circle and triangle functions.
> And if not so, why also not a error functions on the other two.
You have ONE area/1 function; the error message applies to it.
By the way, you are -import+ing math:sqrt/1.
I like that; I appreciate seeing in one place which external
functions are used. But the actual point of -import in Erlang
is to let you call the imported function *without* a module
prefix. That's considered a bad idea, and indeed, you do use
a module prefix. But that means the -import directive was
pointless. You are calling math:pi() without any -import
directive, after all.
I know this is a toy exercise, but I do think I should point out
for the unwary that
>>> area({triangle, A, B, C}) ->
>>> S = (A + B + C)/2,
>>> math:sqrt(S*(S-A)*(S-B)*(S-C));
is a poor way to calculate the area of a triangle.
It's great mathematics, but Kahan ("Dr IEEE floats") has
explained that it is very bad *computationally*.
Let's see if I can approximate his explanation.
Suppose we have a tall skinny triangle, so that A and B are nearly
equal, and C is quite small in comparison. Then S is very nearly
A (and so very nearly B). This means that S-A involves
*catastrophic cancellation*, where the result has a lot fewer
significant digits than you expect.
For example, suppose we have 7 decimal digits of precision,
and A = B = 1000.0, C = 1.0. Then S = 1000.5.
A = 1.000000e3
S = 1.000500e3
S-A = #.###500e3 (using # for 0 to highlight lost significance)
and the result has 3 digits of precision, not 7.
Ah. Here's Kahan's paper: www.cs.berkeley.edu/~wkahan/Triangle.pdf
area({triangle, A, B, C}) ->
0.25*math:sqrt((A+(B+C))*(C-(A-B))*(C+(A-B))*(A+(B-C)));
is an Erlang version of Kahan's improved formula -- assuming,
which I would not advise, that I have not made any mistakes in copying it.
More information about the erlang-questions
mailing list