Stack overflow in Math.bit.2

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Stack overflow in Math.bit.2

fishboy1887
I am getting this error which indicates that there is something going wrong with a while loop somewhere. I step by step debugged through bit and for the arguments 0, 3 it returns -1 which is correct. I initialised the twoToThe array manually instead of using a while loop to avoid any potential errors so I am not sure if this is an error with multiply or with bit itself.

It checks the value inside of twoToThe to see if it and x are equal to 0, it then negates the result to get -1 if true.
    function boolean bit(int x, int i) {
        if (~((x & twoToThe[i]) = 0)) { return true; }
        else { return false; }
    }

This is how I am calling it in multiply, again this seems sound to me so I am not sure where the issue is stemming from.

    function int multiply(int x, int y) {
        var int sum, shiftedx, i;
        let sum = 0;
        let shiftedx = x;
        let i = 0;
        while (i < 16) {
            // Check if i-th bit of y == 1
            if (Math.bit(y, i)) { let sum = sum + shiftedx; }
            let shiftedx = shiftedx + shiftedx;
            let i = i + 1;
        }
        return sum;
    }

I read this thread: http://nand2tetris-questions-and-answers-forum.52.s1.nabble.com/stack-overflow-Math-bit-1-td4031389.html but since I am not using a while loop to initialise twoToThe I do not think this applies
Reply | Threaded
Open this post in threaded view
|

Re: Stack overflow in Math.bit.2

dolomiti7
A stack overflow is most likely linked to recursive calls. Check the call stack in the VM emulator when the program crashes. Though I don't see recursion in your shared code, in your repo you still have a multiplication inside your Math.multiply routine (2 * ...) which would result in an infinite recursion.
Reply | Threaded
Open this post in threaded view
|

Re: Stack overflow in Math.bit.2

fishboy1887
My apologies, I forgot to push the changes. I did change the multiplt to use shiftedx + shiftedx to realise * 2 instead but I believe this issue is most likely to do with divide since it is on the call stack ~30 times. I am going to work on fixing divide and sqrt now since they both use *
Reply | Threaded
Open this post in threaded view
|

Re: Stack overflow in Math.bit.2

fishboy1887
In reply to this post by dolomiti7
Fixed the issue by by replacing x - 2 * q * y with let doubleQ = q + q, if ((x - doubleQ * y) < y {let result = q + q} and then adding in a check to return either the positive or negative result. Thanks for your assistance