Erlang – Numbers

Erlang numbers

In this guide, we will discuss Numbers in Erlang. 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.

Sr.No.Mathematical Functions & Description
1sin
This method returns the sine of the specified value.
2cos
This method returns the cosine of the specified value.
3tan
This method returns the tangent of the specified value.
4asin
The method returns the arcsine of the specified value.
5acos
The method returns the arccosine of the specified value.
6atan
The method returns the arctangent of the specified value.
7exp
The method returns the exponential of the specified value.
8log
The method returns the logarithmic of the specified value.
9abs
The method returns the absolute value of the specified number.
10float
The method converts a number to a float value.
11Is_float
The method checks if a number is a float value.
12Is_Integer
The method checks if a number is an Integer value.

Next Topic : Click Here

This Post Has One Comment

Leave a Reply