Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange division operator in Groovy

Tags:

groovy

I am new to Groovy.

why this throws exception on runtime:

int[] a = [1,2,3,4,5]
int lo=0
int hi=4

int x = a[(lo+hi)/2]
assert x == 3

while these are ok:

int x = a[(int)(lo+hi)/2]

and

int i = (lo+hi)/2
int x = a[i]
like image 396
hint Avatar asked Feb 21 '11 07:02

hint


1 Answers

In groovy a division results in a BigDecimal if the operands are of type Integer, Long, BigInteger or BigDecimal:

See for instance this tutorial:

The division operators "/" and "/=" produce a Double result if either operand is either Float or Double and a BigDecimal result otherwise (both operands are any combination of Integer, Long, BigInteger, or BigDecimal).

[...]

For example

1/2 == new java.math.BigDecimal("0.5");

[...]

Integer division can be performed on the integral types by casting the result of the division. For example:

assert (int)(3/2) == 1I;
like image 185
aioobe Avatar answered Oct 22 '22 19:10

aioobe