Erlang - Numbers


Advertisements


In Erlang there are 2 types of numeric literals which are integers and floats. Following are some examples which show how integers and floats can be used in Erlang.

Integer − An example of how the number data type can be used as an integer is shown in the following program. This program shows the addition of 2 Integers.

Example

-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~w",[1+1]).

The output of the above program will be as follows −

Output

2

Float − An example of how the number data type can be used as a float is shown in the following program. This program shows the addition of 2 Integers.

Example

-module(helloworld).
-export([start/0]). 

start() -> 
   io:fwrite("~w",[1.1+1.2]).

The output of the above program will be as follows

Output

2.3

Displaying Float and Exponential Numbers

When using the fwrite method to output values to the console, there are formatting parameters available which can be used to output numbers as float or exponential numbers. Let’s look at how we can achieve this.

Example

-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~f~n",[1.1+1.2]), 
   io:fwrite("~e~n",[1.1+1.2]).

The output of the above program will be as follows −

Output

2.300000
2.30000e+0

The following key things need to be noted about the above program −

  • When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6.

  • When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6.

Mathematical Functions for Numbers

The following mathematical functions are available in Erlang for numbers. Note that all the mathematical functions for Erlang are present in the math library. So all of the below examples will use the import statement to import all the methods in the math library.

S.No. Mathematical Functions & Description
1 sin

This method returns the sine of the specified value.

2 cos

This method returns the cosine of the specified value.

3 tan

This method returns the tangent of the specified value.

4 asin

The method returns the arcsine of the specified value.

5 acos

The method returns the arccosine of the specified value.

6 atan

The method returns the arctangent of the specified value.

7 exp

The method returns the exponential of the specified value.

8 log

The method returns the logarithmic of the specified value.

9 exp

The method returns the exponential of the specified value.

10 abs

The method returns the absolute value of the specified number.

11 float

The method converts a number to a float value.

12 Is_float

The method checks if a number is a float value.

13 Is_Integer

The method checks if a number is a Integer value.



Advertisements
E-Books Store