Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer division

By definition the integer division returns the quotient.

Why 4613.9145 div 100. gives an error ("bad argument") ?

like image 716
Bertaud Avatar asked Jan 20 '11 16:01

Bertaud


2 Answers

For div the arguments need to be integers. / accepts arbitrary numbers as arguments, especially floats. So for your example, the following would work:

1> 4613.9145 / 100.  
46.139145

To contrast the difference, try:

2> 10 / 10.
1.0

3> 10 div 10.
1

Documentation: http://www.erlang.org/doc/reference_manual/expressions.html


Update: Integer division, sometimes denoted \, can be defined as:

a \ b = floor(a / b)

So you'll need a floor function, which isn't in the standard lib.

% intdiv.erl
-module(intdiv).
-export([floor/1, idiv/2]).

floor(X) when X < 0 ->
    T = trunc(X),
    case X - T == 0 of
        true -> T;
        false -> T - 1
    end;

floor(X) -> 
    trunc(X) .

idiv(A, B) ->
    floor(A / B) .

Usage:

$ erl
...
Eshell V5.7.5  (abort with ^G)
> c(intdiv).
{ok,intdiv}
> intdiv:idiv(4613.9145, 100).
46
like image 129
miku Avatar answered Oct 11 '22 15:10

miku


Integer division in Erlang, div, is defined to take two integers as input and return an integer. The link you give in an earlier comment, http://mathworld.wolfram.com/IntegerDivision.html, only uses integers in its examples so is not really useful in this discussion. Using trunc and round will allow you use any arguments you wish.

like image 24
rvirding Avatar answered Oct 11 '22 14:10

rvirding