Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy error with method mod or %

I just started to program in Groovy, I have got this error and I wanted to see if anyone could help me to work it out.

java.lang.UnsupportedOperationException: Cannot use mod() on this number type: java.math.BigDecimal with value: 5
    at Script1.hailstone(Script1.groovy:8)
    at Script1$hailstone.callCurrent(Unknown Source)
    at Script1.hailstone(Script1.groovy:11)
    at Script1$hailstone.callCurrent(Unknown Source)
    at Script1.hailstone(Script1.groovy:14)
    at Script1$_run_closure1.doCall(Script1.groovy:1)
    at Script1.run(Script1.groovy:1)

I have the following Groovy code

def list = [1,2,3].findAll{it-> hailstone(it)}

def hailstone(num){
    if(num==1){
        return 1;
    }
    println num
    println num.mod(2)
    if(num.mod(2)==0){
        num = num/2;
        return 1 + hailstone(num)
    }else{
        num = 3*num + 1
        return 1 + hailstone(num)
    }
}

​ ​

and the output:

2
0
3
1 
10
0
5

and then it suddenly throws an error on 5.mod(2).

Thanks in advance.

like image 565
Neill Avatar asked Mar 20 '15 02:03

Neill


1 Answers

Looks like 'num' is getting coerced into a BigDecimal when you hit the line num = num/2

If you change the signature of the hailstone method to: def hailstone(int num) it will not crash (because the parameter will get coerced to an int on each invocation), but this may not give the results that you want, as you will lose precision, e.g. when 'num' is an odd number, and num/2 yields a decimal value, the value will be truncated.

For more info on the (sometimes surprising) way that Groovy math operations work, take a look at http://groovy.codehaus.org/Groovy+Math

like image 124
GreyBeardedGeek Avatar answered Nov 09 '22 19:11

GreyBeardedGeek