Search code examples
erlangerlang-otperlang-shell

Tangent by scratch


I'm completely new to Erlang and i'm using the Ubuntu command line to run the program and gedit to edit/write the code.

I'm trying to code tangent my scratch rather than using the built in math class.

I get the following errors and unsure what needs to be changed.

ERROR

** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-0.07926409746793839)
        *** argument 1: is outside the domain for this function
     in call from extra:double/1 (extra.erl, line 11)

CODE

-module(extra).

-export([double/1]).

-import(io,[fwrite/1]).

% I am a comment.

double(N) -> 
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * 2)),
    Tan = Num / Dem,
    io:fwrite("~w",[Tan]).

Solution

  • I think you should be doing a Num * Num instead of Num * 2 when calculating the sqrt for Dem.

    double(N) -> 
        Num = math:sin(N),
        Dem = math:sqrt(1 - (Num * Num)),
        Tan = Num / Dem,
        io:fwrite("~w~n",[Tan]).
    

    As the error clearly says...

    *** argument 1: is outside the domain for this function

    While doing math:sqrt(1 - (Num * 2)), clearly the Num * 2 is becoming more than 1 causing a negative argument to be fed into math:sqrt, and hence the breakage.

    Illustration: sqrt with negative argument

    > math:sqrt(-1).
    math:sqrt(-1).
    ** exception error: an error occurred when evaluating an arithmetic expression
         in function  math:sqrt/1
            called as math:sqrt(-1)
            *** argument 1: is outside the domain for this function
    


    WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET