Groovy error with method mod or %

11,275

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

Share:
11,275
Neill
Author by

Neill

Updated on June 13, 2022

Comments

  • Neill
    Neill almost 2 years

    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.